So now all I'd like in Erlang is...

Richard Carlsson richardc@REDACTED
Fri Feb 20 13:25:13 CET 2004


On Fri, 20 Feb 2004, Joachim Durchholz wrote:

> The reference to Fact is compiled into code that says: "retrieve
> whatever is assigned to the name 'Fact'; crash if Fact is either
> unassigned or assigned something other than a fun; evaluate parameters
> and run the fun with them."

So you want dynamic binding, like in certain Lisp dialects?

The problem with that is of course that if someone passes such a
fun into some other context where Fact is bound to something
completely different (like an integer), it dies horribly.

> > And that's just self-references.  Mutually recursive funs are even more,
> > uh, fun :)  They can be done, of course, but they're far from pleasant.
>
> If you handle them in Y-combinator style, then yes... but it's
> straightforward: just add all the functions to the parameter list.

Yes, you can do it like this:

  Odd0 = fun (0, Odd, Even) ->
               false;
             (N, Odd, Even) ->
               Even(N-1, Odd, Even)
         end,
  Even0 = fun (0, Odd, Even) ->
                true;
              (N, Odd, Even) ->
                Odd(N-1, Odd, Even)
          end,
  Odd = fun (N) -> Odd0(N, Odd0, Even0) end,
  Even = fun (N) -> Even0(N, Odd0, Even0) end

or with a single fun, like this:

  F = fun ({odd, 0}, F) ->
              false;
          ({odd, N}, F) ->
              F({even, N-1}, F);
          ({even, 0}, F) ->
              true;
          ({even, N}, F) ->
              F({odd, N-1}, F)
      end,
  Odd = fun (N) -> F({odd, N}, F) end,
  Even = fun (N) -> F({even, N}, F) end

(It's not _that_ painful...)

	/Richard


Richard Carlsson (richardc@REDACTED)   (This space intentionally left blank.)
E-mail: Richard.Carlsson@REDACTED	WWW: http://user.it.uu.se/~richardc/
 "Having users is like optimization: the wise course is to delay it."
   -- Paul Graham



More information about the erlang-questions mailing list