Y-combinator in Erlang
Hakan Millroth
<>
Tue Jan 7 21:00:19 CET 2003
Now you see why I used to argue that introducing funs etc into Erlang
would make life tougher for the average joe :-)
-- Hakan
On Tuesday, January 7, 2003, at 06:41 PM, Vladimir Sekissov wrote:
> Good day,
>
> I've surprisingly found Y-combinator very useful to solve practical
> problem of writing recursive anonymous functions in Erlang.
>
> Code were translated to Erlang from
> http://www.ece.uc.edu/~franco/C511/html/Scheme/ycomb.html.
>
>
> -module(lambda).
>
> -export([y/1, mk_fact/0]).
>
> %% Y-combinator itself
> y(X) ->
> F = fun (P) -> X(fun (Arg) -> (P(P))(Arg) end) end,
> F(F).
>
> %% Factorial example
> mk_fact() ->
> F =
> fun (FA) ->
> fun (N) ->
> if (N == 0) -> 1;
> true -> N * FA(N-1)
> end
> end
> end,
> y(F).
>
>
> From shell:
>
> 1> F = mk_fact().
> #Fun<lambda.3.115879927>
>
> 2> F(5).
> 120
>
> Best Regards,
> Vladimir Sekissov
More information about the erlang-questions
mailing list