Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign Function from a module to a variable in Erlang?

Tags:

module

erlang

I am new to Erlang. If I do this

H = fun(X) -> X*X.

Then it is fine. But if I move that function to a module, it says "Illegal Expression". For example this

H = misc_functions:square.

Please help.

like image 674
Ram Avatar asked Jan 02 '11 07:01

Ram


2 Answers

Erlang function references require the keyword fun and the arity. Suppose that square takes a single parameter, the correct assignment is:

H = fun misc_function:square/1
like image 91
Little Bobby Tables Avatar answered Sep 23 '22 12:09

Little Bobby Tables


You can also do something like that:

1> F = fun(X) -> misc_function:square(X) end.
#Fun<erl_eval.6.13229925>
2> F(4).
16
3>

Defining a function that calls inside your desired function.

like image 42
Alin Avatar answered Sep 22 '22 12:09

Alin