Functional Programming Using F# and JavaScript

RSS

Anyone who has followed my missives on programming have noted the varied exposure to different programming languages other than the usual C, C++ and Java that embedded programmers utilize. I have expounded on alternatives like Ada (see C Programmers, Time To Try Ada). There has been a smattering of Lisp and other languages that tend to be far afield for embedded programming but there is a method to my madness because they expose programmers to different ways of doing things.

Another area that I see growing in popularity on embedded platforms is the use of scripting languages like JavaScript, Lua (see Accelerate Embedded Development With Lua) and Python. Scripting languages have been popular on servers, workstations and embedded systems with enough processing power but less so as one delves into the lower levels of embedded applications. The move to C and C++ as well as the migration to 32-bit microcontrollers has a bit to do with this trend because the goal is to maximize the developer's effort and higher level languages is a good way to do that. The interactive nature and sandbox isolation from the underlying system are also benefits.

So how do scripting and functional programming come together? Glad you asked.

I would have written about this topic earlier but I was trying to finishing reading an ebook I received entitled Functional Javascript from O'Reilly written by Michael Fogus. It took awhile to wrap my head around the details and I have used functional programming in the past. Even if you do not use JavaScript or plan on doing your next project using functional programming I would still recommend reading the book.

What Fogus did was to implement a functional programming environment using the JavaScript Underscore.js utility library that he wrote.

Now JavaScript is object oriented, a scripting language and it is available on almost every browser. It is part of HTML5 and it can be used as a standalone scripting platform for embedded applications. Adding Underscore.js is easy but it potentially changes the way a programmer will look at things.

First a little about functional programming. I won't try to give you to much. Read the book. That helps and there are hoards of other books on functional programming languages like Haskell, ML and Microsoft's F# (more on that later). This will hopefully be enough to get you to do more research and reading.

Pure functional programming language implementations have no side effects and essentially use immutable, single assignments. That is, you can set X to 1 but once it is set it cannot be changed. That may seem rather tough to deal with compared to the imperative languages like C where reassignment of a variable's value is second nature and necessary to make things work.

Functions are first class objects and partial function application or “currying” can be done to create new functions. Currying is named after Haskell Curry, a noted mathematician and logician (note a naming pattern here). Tail recursion is used instead of iteration from a functional standpoint but another aspect of functional programming is mapping functions across arrays. This tends to be what most for loops do in languages like C.

Another aspect of functional programming is strict versus lazy evaluation. C and most non-functional languages use a strict or eager evaluation so the value of a function's argument is computed before the function is called. Lazy evaluation leaves the computation of the value until it is needed. In some cases it is never needed. Lazy evaluation allows programs to deal with things like infinite lists or lists that are generated on demand. This is a form of stream programming.

So how does I/O get handled? There are things called monads in most functional languages. Wrapping your head around monads can take a week or two but in a nutshell they are things that collect computations. Monads are useful in general but they can also be used to collect operations that can deal with side effects.

So why bend your mind around functional programming and monads for something than mental gymnastics? Well, I have not mentioned things like Haskell's type system and the ability to manipulate programs at a higher level so you can do things like proofs. Proving a C program can be very hard. Doing proofs with a functional programming language is much, much easier.

There is also the idea of distributing computation more easily across a network of computers like the “cloud” because of lazy evaluation and single assignments.

What I have just presented on functional programming just scratches the surface and may not be totally accurate but hopefully it piques your interest.

Anyway, but back to the book Functional JavaScript. The book does a very good job of presenting a number of very difficult ideas including functional programming, implementing it in Javascript and how to utilize it using examples. The advantage is that many of the techniques are easy to use and it is possible to build a program that is a mix of functional and conventional programming methods. Of course, the idea is to use more functional programming to simplify the job and to make it more robust and reliable. The book addresses these issues as well.

I will say that the reason it took me awhile to get through the book is I wanted to understand its implementation or rather how Underscore.js worked in addition to how it can be used. If you just want to use the tools it is a lot easier.

I borrowed this code from Getting Cozy With Underscore.js that is a tutorial on Underscore.js.

  1. var scores = [84, 99, 91, 65, 87, 55, 72, 68, 95, 42],
  2. topScorers = [], scoreLimit = 90;
  3.  
  4. topScorers = _.select(scores, function(score){ return score > scoreLimit;});

It highlights how Underscore.js works and how it gets its name. The underscore (_) above is actually a Javascript object and select is method. In this case, it maps the second argument, a lambda (a function with no name) over a list of values. The result is a sublist that meet the criteria of the lambda function. In this case it would be values above 90.

One neat thing about the Underscore.js website is that the tests for checking out the library are actually done in web pages you can view so you can see how the performance is using your browser.

And where does F# fit in?

This part is actually a follow up to my Visual Studio blog (see A Look At Visual Studio 2013) where I mentioned F#. You probably know that Microsoft is a proponent of C and C++ and it has its own variation called C# that is based on C++. Well, F# is based the ML functional programming language. F# is also in its third major iteration.

Where Underscore.js brings functional programming to JavaScript and browsers, F# brings functional programming to Windows and .NET. Underscore.js and F# may seem like niche platforms but their target platforms are everywhere.

F# plays nice with other languages like C# and it has access to all the .NET functionality that other Microsoft programming languages have access to. F# has also been used to write some interesting and power programs so it is not something just to learn functional programming. Functional programming is used in applications from finance to scientific areas.

So hopefully I have frazzled your brain enough that you want to read more about functional programming, Underscore.js and F#. It is definitely worth the effort. Let me know how you do.

Newsletter Signup

Please or Register to post comments.

What's alt.embedded?

Blogs focusing on embedded, software and systems

Contributors

William Wong

Bill Wong covers Digital, Embedded, Systems and Software topics at Electronic Design. He writes a number of columns, including Lab Bench and alt.embedded, plus Bill's Workbench hands-on column....
Commentaries and Blogs
Guest Blogs
Nov 11, 2014
blog

How to Outsource Your Project to Failure 3

This article will address failure to carefully vet a potential manufacturing or “turnkey” partner and/or failure to transfer sufficient information and requirements to such a partner, a very common problem I have seen again and again with my clients over the years, and have been the shoulder cried upon by several relatives and clients in the past....More
Nov 11, 2014
blog

Transition from the Academe to the Industry Unraveled 1

There have been many arguments here and there about how short-comings of universities and colleges yield engineers with skill sets that do not cater to the demands of the industry. There have been many arguments here and there about an imminent shortage of engineers lacking knowledge in the sciences. There have been many arguments here and there about how the experience and know-how of engineers in the industry may vanish due to the fact that they can’t be passed on because the academic curriculum deviates from it....More
Nov 11, 2014
blog

Small Beginnings 5

About 10 years ago I received a phone call from an acquaintance. He had found a new opportunity selling some sort of investments and he wanted to share it with me in case I was interested. Ken had done fairly well for many years as a contract software developer primarily in the financial services sector. His specialty was writing RPG code. (RPG is often referred to as a write only language.) But he was seeing the handwriting on the wall as the industry moved on to other methods, and saw himself becoming a fossil....More

Sponsored Introduction Continue on to (or wait seconds) ×