[erlang-questions] why can't use anonymous function in escript scripts?

Robert Virding rvirding@REDACTED
Tue Feb 3 19:28:01 CET 2009

2009/2/3 Liu Yubao <yubao.liu@REDACTED>

> Hi,
> `escript a.erl` complains:
> escript: exception error: undefined function erl_eval:myfun/0
> If uncomment the second line, the script works well. It's strange
> I can eval "fun io:format/2." in erl shell.

The reason you can evaluate "fun io:format/2" is that it is a reference to a
function in another module (io) which means that the compiler cannot check
the validity of that reference and so allows it and leaves it up to the
runtime to check if it actually exists. Try evaluating "fun sune:format/2"
to see what happens if module or function does not exist.

I don't know enough about escript to explain why you need to uncomment the
-mode(compile) line, and I don't really understand why it doesn't work. I
think it should.

> Another related counterintuitive thing is I can't evaluate function
> definition in erl shell directly.

The shell evaluates expressions but a function definition is not an

Generally speaking Erlang does not support a seemless interaction between
compiled and interpreted code like most lisp and prolog systems. All
functions must belong to a module and internally there are only (compiled)
modules containing compiled code. To be able to define functions in the
shell which are reachable from other code the shell would have to
(re)compile all its function definitions each time they are changed.

It is not really very much of a hindrance to define functions in a module
and recompile it.


> a.erl:
> -----------------
> #!erl
> %-mode(compile).
> myfun() -> 2.
> main(_) ->
>    io:format("~p~n", [fun myfun/0]).
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20090203/b71ad221/attachment.htm>

More information about the erlang-questions mailing list