views:

613

answers:

3

I'm trying to write a recursive fun in an Erlang shell, but I keep getting an unbound variable exception:

1> Foo = fun(X) -> Foo(X) end.
* 1: variable 'Foo' is unbound

This probably goes without saying, but I'm not trying to create an infinite loop! This is just a simple example of the error I'm getting.

A: 

Obviously, Foo gets assigned only after the fun is defined, so it may not be accessed from within it.

I don't think that Erlang allows to call the anonymous function from itself. Just make it a named one.

IMil
+16  A: 

You can do it with a little argument trick:

1> Foo = fun(F, X) -> F(F, X) end.
#Fun<erl_eval.12.113037538>
2> Foo(Foo, a).
<...infinite loop!>

The trick here is to send in the function as an argument to itself to allow recursion.

Alternative way to make it in one shoot:

1> Foo = fun(X) -> Fun = fun(F,Y) -> F(F,Y) end, Fun(Fun,X) end.
#Fun<erl_eval.6.13229925>
2> Foo(a).

For example:

1> Foo = fun(Max) ->
1>     Fun = fun(F, X) when X > Max -> [];
1>              (F, X) -> [X | F(F, X+1)]
1>           end,
1>     Fun(Fun, 0)
1> end.
#Fun<erl_eval.6.13229925>
2> Foo(10).
[0,1,2,3,4,5,6,7,8,9,10]
Adam Lindberg
I have no experience with Erlang, but it would seem to me that the two arguments a and Foo should be reversed...
Patrick Huizinga
Thanks! It's fixed now!
Adam Lindberg
Does this answer portend the Y-combinator, as mentioned in another answer here?
allyourcode
Well, you could see it as a self-contained ("poor man's") Y-combinator perhaps...
Adam Lindberg
+6  A: 

Alternatively, you can use the Y combinator. Y Combinator in Erlang explains.

Tim Fletcher
Learning about the Y-combinator has been on my list of things to learn for a long time. Thanks for pointing out the opportune moment :). For people who know Scheme, I thought the following page was useful: http://dangermouse.brynmawr.edu/cs245/ycomb_jim.html
allyourcode
Tim, I think this answer could have been better had you briefly mentioned what the Y-combinator is about. I probably would have accepted this answer had you done that.
allyourcode