Y-combinator in Erlang

Joe Armstrong joe@REDACTED
Wed Jan 8 12:31:04 CET 2003


I *strongly* object - the average joe would *not* use the Y combinator
but write factorial thus:

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

        #Fun<erl_eval.11.1870983>
	
This is because the above form looks pretty much like factorial as God
intended it to be written. 

It is called thus:

	> Fac(6, Fac).
        720

/Joe

  Now  how the  average  Håkan might  have  written it  is a  entirely
different matter :-)



On Tue, 7 Jan 2003, Hakan Millroth wrote:

> 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