Wither Self

Richard A. O'Keefe ok@REDACTED
Wed Sep 10 04:19:07 CEST 2003


"Vlad Dumitrescu" <vlad_dumitrescu@REDACTED> wrote:
	> >     {Even, Odd} =
	> >         {fun(0) -> true;  (N) -> Odd( N-1) end,
	> >          fun(0) -> false; (N) -> Even(N-1) end},
	
	is this so much simpler to write and understand than
	
	even(0)->true; even(N)->odd(N-1).
	odd(0)->false; odd(N)->even(N-1).
	
	Even = fun even/1,
	Odd=fun odd/1,
	
Obviously this example would be even simpler as

    Even = fun (N) -> case N rem 2 of 0 -> true; 1 -> false end,
    Odd  = fun (N) -> case N rem 2 of 1 -> true; 0 -> false end,

An oversimplified example constructed to make a different point
entirely (whether my example or Joe Armstrong's) should never be
mistaken for the expected or most typical use of something.

	? Having the funs local may be simpler to write in some cases,
	but once the fun is larger than those above, the code gets rather
	difficult to read.

I presume that Joe's reason for wanting this is to handle the quite
common case where you need a recursive function that can refer to a
local variable.  In that case, it isn't *possible* to just move the
function to the top level; you have to do lambda-lifting.  And then
the function you actually write has a different arity.  And then
you can no longer just pass its name, you have to introduce yet
another fun() to capture the local variable(s) you want.

In short, there are cases where locally defined recursive functions
are harder to read than the alternatives, and, based on Haskell and
ML experience, there are cases where they are much easier to read than
the alternatives.




More information about the erlang-questions mailing list