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

Håkan Huss <>
Thu Mar 29 11:09:34 CEST 2007


On 3/29/07, ok <> 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




More information about the erlang-questions mailing list