[erlang-questions] anyway to make recursion inside anonymous funs?

Robert Virding robert.virding@REDACTED
Thu Mar 29 23:53:33 CEST 2007


Well, that is all well and good but if we really want to do it properly 
(:-)) we should of course use the Y-combinator:

Y = fun (F) ->
          G = fun (X) -> F(fun(Y) -> (X(X))(Y) end) end,
          G(G)
     end.

Yes I know it is ugly with the G but I couldn't be bothered to write it 
out twice.

Then you get:

R = fun (F) ->
        fun (X) ->
             receive {P,V} -> P!(X+V), F(X) end
        end
     end.

and the call:

(Y(R))(X).

Much nicer!

Unfortunately you need a separate Y-combinator for each arity your 
recursing function has. Unless of course you always put them in a tuple 
and so always have one argument.

Robert


Håkan Huss wrote:
> On 3/29/07, ok <ok@REDACTED> wrote:
>> On 29 Mar 2007, at 3:45 am, June Kim wrote:
>>
>>> "fun" expressions can be used to declare a function.
>>> Can [a fun] make a recursive call inside?
>> Let's take
>>      factorial 0 = 1
>>      factorial n = n * factorial (n-1)
>> as an example.
>>
>>
>>     G = fun (_, 0) -> ; (G, N) -> N * G(G, N-1) end,
>>     F = fun (N) -> G(G, N) end
>>
>> We *do* have to give G a name (because F uses G twice);
>> we *don't* have to give F a name.
>>
> Well, obviously we don't *have to* give G a name, or lambda-calculus
> would have severe problems. Not doing so, however, requires you to
> write out the fun previously known as G twice:
> F = fun (N) ->
>             fun (_, 0) -> 1;
>                 (G, N) -> N * G(G, N-1)
>             end
>               (fun (_, 0) -> 1;
>                    (G, N) -> N * G(G, N-1)
>                end,
>                N)
>     end.
> 
>>> Can I somehow declare the following with callself, which is an
>>> imaginary functionality that calls the anonymous function itself?
>>>
>>> fun(X) -> receive {P,V} -> P!(X+V), callself(X+V) end end.
>> This example becomes
>>      ( G = fun (G, X) -> receive {P,V} -> P!(X+V), G(G, X+V) end end,
>>        fun (X) -> G(G, X) end
>>      )
>>
> Without G:
> fun (X) ->
>         fun (F) ->
>                 receive {P,V} -> P!(X+V), F(F) end
>         end (fun (F) ->
>                      receive {P,V} -> P!(X+V), F(F) end
>              end)
> end.
> 
> /Håkan
> 
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
> 



More information about the erlang-questions mailing list