[erlang-questions] re cursive fun()

Edwin Fine <>
Sun Oct 5 11:13:41 CEST 2008


I'm assuming that you want to do this in the shell, otherwise it would be
easier just to write the function in the usual way, e.g.

myfun() ->
    blah, blah,
    myfun().

To create a fun that calls itself, you must realize that you are creating an
unnamed function. When you write

fun(X) -> X * 2 end.

this is compiled to a Fun data type, e.g. #Fun<erl_eval.6.13229925>.

Since the function does not have a name, it cannot refer to itself.

When you write FunVar = fun(X) -> X * 2 end, the function is bound to the
variable FunVar. Because the binding takes place *after* the fun is created,
the fun cannot refer to the variable FunVar within its definition.

So how is it done? You have to pass the variable to the function so that it
"knows" what to call:

FunVar =
   fun(MySelf) ->
      ...
      MySelf().

Then when you call it, you call FunVar(FunVar). Looks strange but it works.

Example: Writing a simple generate and fold function using only a fun()
variable.

9> GenFold =
   fun(0, Acc, _) ->
      Acc;
   (X, Acc, Fun) ->
      Fun(X - 1, [X|Acc], Fun)
   end.
#Fun<erl_eval.18.105910772>
10> GenFold(10, [],
GenFold).
[1,2,3,4,5,6,7,8,9,10]
11>

Or a for loop:

22> For =
    fun(Max, Max, ExecFun, _) ->
       ok;
   (N, Max, ExecFun, Next) ->
      ExecFun(N),
      Next(N + 1, Max, ExecFun, Next)
   end.
#Fun<erl_eval.4.105156089>
23> For(0,10,fun(I) -> io:format("~B ", [I]) end,
For).

0 1 2 3 4 5 6 7 8 9 ok
24>

Stuff like this is described in Joe Armstrong's Erlang book.

Hope this helps.

On Sat, Oct 4, 2008 at 11:19 PM, deepblue_other <> wrote:

>
> hello
> I have this going on
>
> FunVar =
>   fun() ->
>      ...
>      FunVar()
>   end.
>
> so the compiler is complaining that FunVar is unbound at the place where
> its
> being used inside fun(); this makes sense, however Im wondering how to make
> this into a recursive function since there's no name to reference the
> function with.
>
> thanks
> --
> View this message in context:
> http://www.nabble.com/recursive-fun%28%29-tp19820386p19820386.html
> Sent from the Erlang Questions mailing list archive at Nabble.com.
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20081005/26131d48/attachment.html>


More information about the erlang-questions mailing list