[erlang-questions] re cursive fun()

Ciprian Dorin Craciun <>
Sun Oct 5 16:11:57 CEST 2008


On Sun, Oct 5, 2008 at 12:30 PM, Richard Carlsson <> wrote:
> 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.
>
> You have to make it keep "itself" around as an additional parameter,
> so that you can first create it and then hand it the self-reference:
>
> FunVar =
>   fun(Myself) ->
>       ...
>       Myself(Myself)
>    end
>
> then call it like this:
>
> FunVar(FunVar).
>
> If you want the result to be a function of arity 0,
> as in your example, then replace the last line with
>
> FinalFunVar = fun () -> FunVar(FunVar) end
>
>    /Richard
>
> --
>  "Having users is like optimization: the wise course is to delay it."
>   -- Paul Graham


    About this subject, I would ask if isn't it better / easier /
clearer to add a special function name / keyword that would refer to
the function itself. This would also have a few advantages:
    * first it will solve the recursivity problem described above;
    * (maybe) it could also improve efficiency (because you know
exactly what function you're calling, without any lookup); (this is
just an assumption, maybe inside the beam file the lookup does not
exist); (certainly it is more efficient than the proposed solution ---
sending the function as an argument;)
    * it will assist in refactoring --- changing a recursive function
name will have no impact on it's code;
    * it could clearly mark the fact that the function calls itself.

    As for disadvantages I really do not see any. (Except of having a
new keyword / special function.)

    So any comments?

    Ciprian.

    P.S.: I think this solution could be equally applied to all
languages (mainly Lisp like).



More information about the erlang-questions mailing list