tags:

views:

169

answers:

4

Is there a way to have a full interpreter in Erlang, not just a "shell".

Since it is a dynamic language, not being able to define named functions in the interpreter is a little bit disappointing... I suspect that it is because compilation units (modules) must be explicitly compiled for their execution by the VM, but maybe a REPL acting as a dynamic/recompilable module exist?

A: 

Reading from: http://www.chicagolug.org/wiki/Erlang

Erlang provides a REPL (read, eval, print, loop) that allows you to run Erlang code, compile source files and run functions from those newly compiled Erlang source files which can be started after you have installed Erlang with the command erl. When showing use of the REPL instead of a source file the code will look like:

> c(helloworld).
> helloworld:hello_world(). Distinguishable by the '>' before the

commands. If you can't tell, the above commands in the REPL compile our previous hello world program, notice the compile function, c, takes the module name no the source file name, and then runs the exported function hello_world.

You can also load a new compiled module with:

> l(helloworld).
Roberto Aloi
Yes, I understand, but what I am looking for is a way to define the hello_world() function directly from the REPL, without having to write a source file (like in LISP for example)
Gabriel Cuvillier
Well, then just define your own funs as explained in the other answers.
Roberto Aloi
Also, the reason I didn't suggest you to use Funs at the beginning is because they are not extremely convenient in the shell, unless the body of the function is really simple (say, writable in a couple of lines). Managing typos and errors can be a pain for long funs' bodies...
Roberto Aloi
+2  A: 

F= fun () -> io:format("Hello World~n", []) end.

F().

eolo999
Welcome to SO :)
Roberto Aloi
+1  A: 

The short answer is NO, it does fit into the way that Erlang handles code.

The Erlang VM only supports compiled code. The unit of code handling, including compilation, is the module, you load, delete, update and purge modules. So it is not really possible to mix interpreted and compiled functions the same way as you can in lisp. It would be possible to extend the shell to allow defining interpreted functions within it but these would then only be callable from within shell interpreter and not from other modules. It would also be possible to make the shell recompile and reload "shell module" so functions within it could be called from other modules. But this module would then only really exist within that invocation of erlang.

And I honestly don't really see the point as recompiling and reloading code has always been so fast it has not been a problem. It would more be force of habit than convenience.

rvirding