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.
I had a need to quickly send some packets over UDP for testing and here is how I have done it using the samples above:
After Erlang 17, you can also use the "Funs with names" variant:
In this way it is easier to understand that
F
is the function itself within the definition. Also,Foo
andF
can be the same variable.You can do it with a little argument trick:
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:
For example:
Since OTP 17.0 there are named funs which makes the task a lot easier:
Alternatively, you can use the Y combinator. Y Combinator in Erlang explains.
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.