Y-combinator in Erlang

Vladimir Sekissov svg@REDACTED
Tue Jan 7 18:41:21 CET 2003


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