Fun syntax

Matthias Lang <>
Tue Jul 30 10:46:29 CEST 2002


Vlad Dumitrescu writes:

 > I am a little confused about the syntax for functional objects when the 
 > referred function is remote. The way to define a fun is then
 >     Fun = {lists, reverse}

 > I find this a little inconsequent. Why not
 >     Fun = fun lists:reverse/1 ?

Are you mixing up several weakly-related issues? The tuple syntax for
funs is deprecated and has (almost?) nothing to do with 'local' or
'remote'. You can use the same fun syntax to send funs between local
and remote processes. Example:

   -------------------a.erl--------
   -module(a).
   -export([make_fun/0]).
   
   make_fun() -> 
           fun(X) -> lists:reverse(X) end.
   
   -------------------one node---------
   ()3> F = a:make_fun().
   #Fun<a.0.102191654>
   ()4> pid(230,53,0) ! F.
   #Fun<a.0.102191654>
   
   -------------------another node--------- 
   ()1> self().
   <230.53.0>
   ()2> F = receive X -> X end.
   #Fun<a.0.102191654>
   ()3> F([1,2,3]).
   [3,2,1]

The only coupling between "remote" and "local" I can think of in
relation to funs is that the code for the fun must be available on the
node it is executed on, i.e. if '' doesn't have access to
'a.beam', you get

   ** exited: {undef,[{#Fun<a.0.102191654>,[[1,2,3]]},
                     {erl_eval,expr,3},
                     {erl_eval,exprs,4},
                     {shell,eval_loop,2}]} **

In the example, the problem CAN be avoided by sending a "tuple-fun",
but you're up the proverbial shit creek without a paddle if the fun()
you wanted to send was something more complex, for instance:

   fun(X) -> lists:duplicate(lists:reverse(X)) end

So:

  1. You shouldn't be using the tuple syntax

  2. It is possible to abuse the tuple syntax to work around some 
     fundamental design decisions in Erlang, but the result is
     ugly and non-general, and mucking around with the syntax won't
     fix that.

BTW, take a look at what happens if you send a fun() you define in the
shell around. It sends the code for the fun in the message. ;-)

Matthias



More information about the erlang-questions mailing list