Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are multi-arity anonymous functions possible in Erlang?

Tags:

erlang

I am in a situation where I can only create anonymous functions that are assigned to a variable, like this:

Foo = fun(X) -> X end.

I know if you are in a module you can do something like this:

foo(X) -> X.
foo(X, Y) -> X + Y.
% i.e. foo(3) = 3, foo(3,4) = 7

My questions is: is this possible with anonymous functions?

A blog post (that I've now lost sorry) led me to think you could do something like this:

Foo = fun(X) -> X;
         (X, Y) -> X + Y
      end.

But that does not work, as I get a "head mismatch" error.

like image 875
SCdF Avatar asked Jan 07 '16 10:01

SCdF


1 Answers

The simple and correct answer is no, you can't. This is actually quite logical as when you do

foo(X) -> X.
foo(X, Y) -> X + Y.

you are actually creating two functions: foo/1, a function of one argument; and foo/2, another function which has two arguments. They are not the same foo. This maps directly to anonymous functions (funs) so you would need to create two different funs, one of one argument and the other of two arguments.

The "head mismatch" error is complaining about the different number of arguments.

like image 65
rvirding Avatar answered Nov 15 '22 22:11

rvirding