[erlang-questions] erl_eval function object

Hans Bolinder hans.bolinder@REDACTED
Thu Aug 20 13:40:52 CEST 2009


[Paul Mineiro:]
> The documentation for erl_eval says that the NonlocalFunctionHandler is
> called when a functional object (fun) is called; however I'm not seeing
> this.

> -----
> -module (evaltest).
> -compile (export_all).
> 
> doit (String) ->
>   { ok, Scanned, _ } = erl_scan:string (String),
>   { ok, Parsed } = erl_parse:parse_exprs (Scanned),
>   Bindings = erl_eval:new_bindings (),
>   erl_eval:exprs (Parsed,
>                   Bindings,
>                   { value, fun local/2 },
>                   { value, fun non_local/2 }).
> 
> local (Name, Arguments) ->
>   io:format ("local ~p ~p~n", [ Name, Arguments ]),
>   false.
> 
> non_local (FuncSpec, Arguments) ->
>   io:format ("non_local ~p ~p~n", [ FuncSpec, Arguments ]),
>   case FuncSpec of
>     { M, F } -> erlang:apply (M, F, Arguments);
>     Func when is_function (Func) -> erlang:apply (Func, Arguments)
>   end.
> -----
> 
> % erl
> Erlang (BEAM) emulator version 5.6.5 [source] [smp:2] [async-threads:0] [kernel-poll:false]
> Eshell V5.6.5  (abort with ^G)
> 1> evaltest:doit ("(fun () -> 10 + 2 end) ().").
> non_local {erlang,'+'} [10,2]
> {value,12,[]}

There is a functional object for every fun-end expression, and it is
created in one of the clauses of the erl_eval:expr/5 function. As
indicated by the "ugly hack" comment in that clause, the fun's
existence is an implementation detail; it is possible (but unlikely)
that some day the fun will no longer be needed. When evaluating
expressions erl_eval does a careful job not to call the non-local
function handler function for such "helper" funs.

The non-local function handler will be called with the fun as the
first argument in cases like this:

1> evaltest:doit ("(fun math:sqrt/1) (2).").
non_local #Fun<math.sqrt.1> [2]
{value,1.4142135623730951,[]}

Best regards,

Hans Bolinder, Erlang/OTP team, Ericsson


More information about the erlang-questions mailing list