[erlang-questions] calling fun() from fun()

Robert Virding <>
Sat Jun 2 23:44:00 CEST 2007


That's easy, you need the Y-combinator!

y(M) ->
     G = fun (F) -> M(fun(A) -> (F(F))(A) end) end,
     G(G).

  and then you define you fun with a fun wrapper like so:

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

and call it like:

(y(Fac))(5)
120

Voila! No need to add extra arguments or anything. It only works for 
funs of one argument, but, hey, what are tuples for?

Robert

P.S. You're code examples came out real funny in the mail.

datacompboy wrote:
> that's easy!
> 
> FibI = fun
>   (X,_) when X<1 -> throw(badarith);
>   (1,_) -> 1;
>   (2, _) -> 1;
>   (X,FibI) -> FibI(X-1,FibI)+FibI(X-2,FibI)
> end,
> Fib = fun(X) -> FibI(X, FibI) end,
> Fib(10).
> 
> 
> it produce correct result -- 55.
> So, you just should pass it to itself, and if you must use one-arg fun (for example, to pass it to somewhere), make additional fun that will call real fun with additional arg.
> --
> --- suicide proc near\n call death\n suicide endp
> _________________________________________________________
> Post sent from http://www.trapexit.org
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions
> 



More information about the erlang-questions mailing list