[erlang-questions] re cursive fun()
Sun Oct 5 17:03:49 CEST 2008
Just noticed a mistake.
should have been
On Sun, Oct 5, 2008 at 5:13 AM, Edwin Fine
> 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,
> 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) ->
> 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()
> 9> GenFold =
> fun(0, Acc, _) ->
> (X, Acc, Fun) ->
> Fun(X - 1, [X|Acc], Fun)
> 10> GenFold(10, ,
> Or a for loop:
> 22> For =
> fun(Max, Max, ExecFun, _) ->
> (N, Max, ExecFun, Next) ->
> Next(N + 1, Max, ExecFun, Next)
> 23> For(0,10,fun(I) -> io:format("~B ", [I]) end,
> 0 1 2 3 4 5 6 7 8 9 ok
> 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:
>> I have this going on
>> FunVar =
>> fun() ->
>> so the compiler is complaining that FunVar is unbound at the place where
>> being used inside fun(); this makes sense, however Im wondering how to
>> this into a recursive function since there's no name to reference the
>> function with.
>> View this message in context:
>> Sent from the Erlang Questions mailing list archive at Nabble.com.
>> erlang-questions mailing list
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the erlang-questions