[erlang-questions] re cursive fun()
Sun Oct 5 17:12:21 CEST 2008
Edwin Fine-2 wrote:
> 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,
no shell is not the reason, I need a function that will only be called from
within another function and I dont want to "pollute" the "module wide" space
with another function, so Im putting in a nested one...
I would prefer to declare a regular function, but as far as I know there are
no nested functions in Erlang (regular named functions).
Edwin Fine-2 wrote:
> To create a fun that calls itself, you must realize that you are creating
> 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
> 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
> "knows" what to call:
> FunVar =
> fun(MySelf) ->
> Then when you call it, you call FunVar(FunVar). Looks strange but it
> 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
> erlang-questions mailing list
what you have described makes perfect sense
View this message in context: http://www.nabble.com/recursive-fun%28%29-tp19820386p19825467.html
Sent from the Erlang Questions mailing list archive at Nabble.com.
More information about the erlang-questions