Haskell’s foldr in JavaScript

Most people who work with me know that I’m a great fan of the Haskell programming language. I believe (as do most fans of the language) that a firm grasp of Haskell will help you become a better programmer generally. I feel, furthermore, that one of the contexts where this benefit is most pronounced is in JavaScript programming.

foldr in JavaScript:

And so, for use in my scripts, I’ve implemented Haskell’s famous foldr function in JavaScript. Source below:

function foldr(fn, ult, xs) {
  if (xs.length == 0) {
    return ult;
  }
  if (xs.length == 1) {
    return fn(
      xs[0],
      ult
    );
  }
  else {
    return fn(
      xs.splice(0, 1)[0],
      foldr(
        fn,
        ult,
        xs
      )
    );
  }
}

What, in Haskell we might write as:

foldr (\x y -> (x+y)/2) 54 [12,4,10,6]
--  Output: 12.0

In JavaScript we can write:

foldr (function(x, y){ return (x+y)/2; }, 54, [12,4,10,6])
// Output: 12

So, there it is. I hope you like it.

Further Pondering:

But before I go, I want to write some philosophical thoughts on Haskell and JavaScript.

The similarities between the two are more than passing. They are both functional languages. As Douglas Crawford points out, JavaScript was the first popular “lambda-language”. Both languages have proven to be highly expressive tools for programmers despite being occasionally unforgiving in syntax.

Aside: Curiously, some of the most clever programs have be written in the most austere environments. I’m reminded of the quote:

“More good code has been written in languages denounced as bad than in languages proclaimed wonderful — much more.”
Bjarne Stroustrup

End aside.

However, the differences between Haskell and JavaScript become conspicuous. Whereas Haskell is statically typed and strictly functional, JavaScript is quite dynamic and is generally written procedurally. These features lead to common pitfalls in JavaScript, where scripts can turn into “spaghetti-code” or soupy variable messes of “side-effects“. Haskell itself is sheltered from these dangers by virtue of strong typing and restriction to the functional paradigm.

For these reasons, it’s my belief that taking experiences from Haskell programming into JavaScript algorithms results in safer, more reliable, more verifiable code. In the realm of JavaScript and the problems particular to it, these qualities are of paramount value.

In this spirit, I may find myself porting more of the Haskell prelude functions in the future.