I have following elixir code snippet:
defmodule Rectangle do
def area(a, b) do
a * b
end
def area(a) do
a * a
end
end
Then I load the file into iex session as follow:
iex(1)> import_file "rectangle.exs"
{:module, Rectangle,
<<70, 79, 82, 49, 0, 0, 5, 84, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 204, 131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>,
{:area, 1}}
It works fine like I expected
iex(2)> Rectangle.area(9)
81
Now I want to assign the area function with arity 1 to anonymous function like:
iex(3)> fun = Rectangle.area/1
** (UndefinedFunctionError) undefined function Rectangle.area/0
Rectangle.area()
But when I typed like:
iex(3)> fun = &Rectangle.area/1
&Rectangle.area/1
Then it works. Why do elixir expect & in front of the function name, although Rectangle.area is already a function?
12.3) A set of functions for working with functions. Anonymous functions are typically created by using fn : iex> add = fn a, b -> a + b end iex> add.(
Elixir provides a shorthand for calling anonymous functions. It's called the capture operator. It's represented by an ampersand and it's used to replace the fn, the forward facing arrow and the end.
In order to create our own modules in Elixir, we use the defmodule macro. The first letter of the module must be in uppercase. We use the def macro to define functions in that module. The first letter of every function must be in lowercase (or underscore):
It is because that's how the compiler parses an anonymous function.
Rectangle.area/1
would parse as a division of Rectangle.area
to 1
(hence the undefined function Rectangle.area/0
error).
You can see how an expression is parsed using quote
:
iex> quote do &Rectangle.area/1 end
iex> quote do Rectangle.area/1 end
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