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

ok <>
Thu Mar 29 02:30:55 CEST 2007

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.

We'd have to have

     F = fun (0) -> 1; (N) -> N * F(N-1) end

This doesn't work, because the compiler reckons the second occurrence
of F is unbound.  So the body of F will have to use some other variable,
call it G.  But we can't provide the value of G until after the value to
be bound to F is created, so G will have to be a parameter.

    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.

In general,
    F = fun (...) -> ... F(...) ... end
turns into
    G = fun (G,...) -> ... G(G,...) ... end,
    F = fun (...) -> G(G,...) end
A group of mutually recursive functions can be handled by adding an
argument for each.

> 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

More information about the erlang-questions mailing list