do_stuff() ->
GetAnswer = fun() -> 42 end,
spawn(fun() -> io:format("The answer is ~p\n", [GetAnswer()]) end).
Here, GetAnswer is a closure, as is the anonymous function given to spawn() function.I've, been programming for 20+ years and I look at that code and say what the f*k?
Ooh, it's the functional stuff. Ok, move on.
Let me take you through it:
do_stuff() ->
This declares a function do_stuff(). It's exactly like: function do_stuff() { ... }
Everything after is the body. Unlike many languages, Erlang uses comma, not semicolons, as statement separators, function bodies end with a "." so a function follows the form: do_stuff() -> a, b, c.
Here, a, b and c are statements. The last statement provides the return value. This directly translates to: function do_stuff() { a; b; return c; }
Next line defines a variable: GetAnswer = fun() -> 42 end,
This just defines a variable which is an anonymous, inline function, sometimes called a closure or a lambda (all three are technically correct). In Erlang, anonymous functions end with "end", not ".". This is equivalent to JavaScript: var GetAnswer = function() { return 42; };
The next line is therefore easy to understand, as it uses the same inline function syntax; it calls spawn() with this function as an argument. So it's this: spawn(...)
The argument is this function: fun() -> io:format("The answer is ~p\n", [GetAnswer()]) end
JavaScript version: function() { return io.format(
"The answer is ~p\n", [GetAnswer()]); }
(Of course, JS doesn't have spawn() or io.format(); this is just syntax.)Complete version:
function do_stuff() {
var GetAnswer = function() { return 42; };
spawn(function() {
io.format("The answer is ~p\n", [GetAnswer()]); });
}
In some ways, the JavaScript version is actually gnarlier. Look at all those braces and semicolons.The thing is, the syntax we found nice is usually nice because it's familiar. Many languages could seem like an incomprehensible mess if you're used to C-style brace syntax. But that's purely a question of familiarity. If you don't know what all the bits and pieces mean, you're going to be alienated by it. A developer who has grown up on COBOL and Forth will not find JavaScript syntax familiar any more than you find Erlang syntax familiar.
I suggest stepping out of your comfortable protective shell and trying it out. It's not rocket science. After 30-60 minutes reading this book you'll no longer find it alien, I bet: