[erlang-questions] Self-referencing anonymous functions?

Rob Charlton <>
Thu Apr 2 22:28:53 CEST 2009


Perhaps a step too far, but it's fun (no pun intended): you could also 
use the Y-combinator:

1> Y = fun(M) ->
1>     G = fun (F) -> M(fun(A) -> (F(F))(A) end) end,
1>     G(G) end.
#Fun<erl_eval.6.13229925>

Then define Total using a surrounding function-that-takes-a-function:

2> Total2 = fun(F) -> fun([{N,C}|T]) -> N*C + F(T);([])-> 0 end end.
#Fun<erl_eval.6.13229925>

Then your actual Total function can be used by:

3> (Y(Total2))([{2,3},{4,1},{9,7}]).
73

Or you can then define Total by:

4> Total = Y(Total2).
#Fun<erl_eval.6.13229925>

and use it:
5> Total([{2,3},{4,1},{9,7}]).
73

See: http://bc.tech.coop/blog/070611.html if you're interested in this.

Cheers

Rob


Thomas Allen wrote:
> Hi all,
>
> I'm just getting going with Erlang (using Armstrong's book) and I ran
> into anonymous functions. I tried translating the shop:cost and
> shop:total functions, but I cannot translate the latter because it
> refers to itself. How would I rewrite this to not throw errors?
>
> Total = fun ([{What, N}|T]) ->
>         Cost(What) * N + Total(T); % Clearly, "Total" won't fly here
>     ([]) -> 0
> end.
>
> Thanks,
> Thomas
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions
>   


-- 
Rob Charlton
Savage Minds Ltd
+44 20 79210521

skype: chocolatetpot
www.savageminds.com




More information about the erlang-questions mailing list