Damien Katz Criticizes Erlang

March 10th, 2008  |  Published in code, erlang, functional  |  3 Comments  |  Bookmark on Pinboard.in

Damien Katz has been using Erlang for CouchDB, and has posted some criticisms of the language and runtime based on his experiences with them. Erlang, like any language, has its issues, and Damien’s criticisms are mostly reasonable and are worth reading. Well, except for this one:

Immutable variables in Erlang are hard to deal with when you have code that tends to change a lot, like user application code, where you are often performing a bunch of arbitrary steps that need to be changed as needs evolve.

In C, lets say you have some code:

int f(int x) {
x = foo(x);
x = bar(x);
return baz(x);
}

And you want to add a new step in the function:

int f(int x) {
x = foo(x);
x = fab(x);
x = bar(x);
return baz(x);
}

Only one line needs editing,

Consider the Erlang equivalent:

f(X) ->
X1 = foo(X),
X2 = bar(X1),
baz(X2).

Now you want to add a new step, which requires editing every variable thereafter:
f(X) ->
X1 = foo(X),
X2 = fab(X1),
X3 = bar(X2),
baz(X3).

If you had to write that code the way Damien did, then yes, that would suck. But here’s a better way to write it:

f(X) ->
    lists:foldl(fun(F, Last) -> F(Last) end,
        X, [fun foo/1, fun fab/1, fun bar/1, fun baz/1]).

This code applies the anonymous function passed as the first argument to lists:foldl for each element of the third argument — the list of funs, Erlang-speak for functions — starting with the value X as the value passed as Last and using the return value of F(Last) as the next value of Last. The overall return value of lists:foldl is the final value of Last. With this approach, modifying the functions applied to X also requires editing only a single line, specifically the list of funs.

In general, if you’re used to imperative languages and you find yourself writing step-by-step Erlang code like in the original example above, think functions and lists instead.

P.S. If you’ve never seen it, read Damien’s Signs You’re a Crappy Programmer (and don’t know it). One of my favorite blog postings, and I especially like the first two items in his list.

Responses

  1. Kevin Scaldeferri says:

    March 10th, 2008 at 12:38 pm (#)

    I guess I don’t understand why

    f(X) -> baz(bar(fab(foo(X))))

    isn’t considered superior to both of these.

  2. steve says:

    March 10th, 2008 at 4:24 pm (#)

    Kevin: I think that’s fine too, as long as there’s just a few such functions. If I had a long list of functions, though, I’d use my approach, and would bind the fun list to a variable on a separate line to make it clearer. Also, your approach assumes that the result of one funcall is fed directly into the next, where using foldl allows the result to be manipulated before being passed to the next funcall.

  3. Erlang Tidbits | Programmer’s Paradox says:

    March 10th, 2008 at 11:52 pm (#)

    […] Partial Rebuttal of Why Erlang Sucks […]