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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With