[erlang-questions] re cursive fun()

Alpár Jüttner <>
Sun Oct 5 18:52:30 CEST 2008


You may do a trick like this:

1> Fact = fun(0) -> 1; (N) -> Fun=get(fact), N*Fun(N-1) end.
#Fun<erl_eval.6.13229925>
2> put(fact,Fact).
undefined
3> Fact(5).
120

Regards,
Alpar


On Sun, 2008-10-05 at 09:07 -0700, deepblue_other wrote:
> so definitely no named nested functions?
> 
> Zvi wrote:
> > 
> > Otherwise, than passing the Fun as argument to itself, one can implement
> > recursive functions, using code, like this:
> > 
> > fact(0) -> 1;
> > fact(N) when N>0 ->
> >             {M,F,_A} = element(2,process_info(self(),current_function)),
> >             N * {M,F}(N-1).
> > 
> > But this doesn't work for funs, if there are was something like:
> > 
> > Fact = fun(0) -> 1;
> >                (N) when N>0 ->
> >                     Fun = element(2,process_info(self(),current_fun)),
> >                     N * Fun(N-1).
> > 
> > Zvi
> > 
> > 
> > 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
> >> 
> > 
> > 
> 




More information about the erlang-questions mailing list