[erlang-questions] Auto generated functions

Hynek Vychodil <>
Thu Feb 7 12:49:19 CET 2008


Why if you can just use "half" of Y combinator:

3> LenGen = fun(_, []) -> 0; (This, [_|T]) -> This(This, T)+1 end,
3> Len = fun(L) -> LenGen(LenGen, L) end.
#Fun<erl_eval.6.49591080>
4> Len([a,b,c]).
3
5> Len([]).
0
6> Len(lists:seq(1,100)).
100
7> Len2 = begin G = fun(_, []) -> 0; (This, [_|T]) -> This(This, T)+1 end,
fun(L) -> G(G, L) end end.
#Fun<erl_eval.6.49591080>
8> Len2([]).
0
9> Len2([a,b,c]).
3
10> Len2(lists:seq(1,100)).
100

this() is only syntactic sugar and object oriented approach (not
functional).

On Feb 6, 2008 11:03 PM, Zvi <> wrote:

>
> Y-combinator is cool, but I'm just currious why Erlang doesn't have some
> mechanism allowing fun to reference to itself (doesn't mutter if it's
> named
> or annonymous fun), same way as every process can get it's own PID using
> self(), i.e. (here I using this() to reference to function from inside):
>
> Len = fun([]) -> 0;
>             ([_|T]) -> this()(T)+1 end.
>
> Is there something in BEAM instruction set, that preventing from
> implementing this?
>
> thanks,
> Zvi
>
>
> Christian S wrote:
> >
> > On Feb 4, 2008 11:39 PM, Attila Babo <> wrote:
> >> I wrote a simple Y combinator to deal with tail-recursive anonymous
> >> functions. There are several showcase implementations for Erlang
> >> already, but for practical purposes you need to deal with arity. Here
> >> is my code with examples, I'm looking for a way to avoid this
> >> boilerplate code. For practical reasons it's OK to generate it up to a
> >> point by hand or use a single tuple as a parameter, but I'm looking
> >> for "nicer" solution. Any suggestions?
> >
> > That's the way its done. Only improvement would be to use the
> > erlang:is_funciton/2 guard. But that is not likely what you were looking
> > for.
> > _______________________________________________
> > erlang-questions mailing list
> > 
> > http://www.erlang.org/mailman/listinfo/erlang-questions
> >
> >
>
> --
> View this message in context:
> http://www.nabble.com/Auto-generated-functions-tp15279499p15312902.html
> Sent from the Erlang Questions mailing list archive at Nabble.com.
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions
>



-- 
--Hynek (Pichi) Vychodil
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20080207/1ac2f343/attachment.html>


More information about the erlang-questions mailing list