Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define an function in the eshell (Erlang shell)?

Is there any way to define an Erlang function from within the Erlang shell instead of from an erl file (aka a module)?

like image 406
yazz.com Avatar asked Jan 14 '10 17:01

yazz.com


People also ask

How do you define a function in erlang?

A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions. A function named f in the module m and with arity N is often denoted as m:f/N.

Which of the following is the correct syntax to define a function in the erlang shell?

Syntax − f(x). Where, x – is the variable for which the binding needs to be removed. For example − Following is an example of how the function is used. First a variable called Str and Str1 are defined.

How do you define a record in erlang shell?

If you want to experiment with records at the command line, you'll have to use a shell command. Let's try that in the erlang shell tool, erl . And then you can declare a record the same way you would in Erlang. And to inspect that variable in erl, just declare the variable and put a .


2 Answers

Yes but it is painful. Below is a "lambda function declaration" (aka fun in Erlang terms).

1> F=fun(X) -> X+2 end. %%⇒ #Fun <erl_eval.6.13229925> 

Have a look at this post. You can even enter a module's worth of declaration if you ever needed. In other words, yes you can declare functions.

like image 98
jldupont Avatar answered Sep 20 '22 12:09

jldupont


One answer is that the shell only evaluates expressions and function definitions are not expressions, they are forms. In an erl file you define forms not expressions.

All functions exist within modules, and apart from function definitions a module consists of attributes, the more important being the modules name and which functions are exported from it. Only exported functions can be called from other modules. This means that a module must be defined before you can define the functions.

Modules are the unit of compilation in erlang. They are also the basic unit for code handling, i.e. it is whole modules which are loaded into, updated, or deleted from the system. In this respect defining functions separately one-by-one does not fit into the scheme of things.

Also, from a purely practical point of view, compiling a module is so fast that there is very little gain in being able to define functions in the shell.

like image 23
rvirding Avatar answered Sep 22 '22 12:09

rvirding