Re:Erlang/OTP 17.0 has been released
by mononcqc on Wednesday April 09, 2014 @02:22PM
(#7561215)
The syntax would actually be:
Note that the name `Fac` is not visible outside of the fun's scope, and to use the same variable name outside, you still need to bind it:
[ Parent
| on HN ]
Looks like this is pretty much identical to JavaScript?
Pretty much. Javascript has the same scoping rules for functions used as expressions:
var f = function fac(n) { if (n==0) { return 1; } else {return fac(n-1)*n; } };
console.log(f(3));
console.log(fac(3));
This will log '6' and error out on the last one (fac is undefined). This is the same scoping Erlang uses for anonymous function names as far as I can tell, with one difference: Erlang's function name is a variable that can be used as such internally. In Javascript, the function name doesn't refer to a variable per se: var f = function fac() { console.log(fac) };
console.log(f);
f();
Which will log 'fac()' and 'undefined'. In Erlang: 1> F = fun Fac() -> Fac end.
#Fun<erl_eval.44.71889879>
2> F().
#Fun<erl_eval.44.71889879>
Both instances (F and Fac within the right scope) return the same anonymous function.Are you sure you didn't make a mistake, and confuse the undefined that f() returned with an undefined output from the console.log(fac)? It looks to me like the function is a perfectly normal variable.
var f = function foo() { console.log('Me:', foo); }
f();
Me: function foo() { console.log('Me:', foo); }
undefinedYou're right, I've been fooled by Firebug merging in multiple identical output lines together and missed the (2) it had put on the right hand side of the screen. That makes a lot more sense.