Why the elixir capture operator needs to bind a function to a value

I have the 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 upload the file to an iex session as follows:

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 as I expected

iex(2)> Rectangle.area(9)
81

Now I want to assign an area function with arity 1 to an anonymous function, for example:

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 does the elixir also wait in front of the function name, although Rectangle.area is already a function?

+4
source share
1 answer

Precisely because the compiler parses an anonymous function.

Rectangle.area/1will be analyzed as division Rectangle.areaby 1(hence, error undefined function Rectangle.area/0).

You can see how the expression is parsed with quote:

iex> quote do &Rectangle.area/1 end
iex> quote do Rectangle.area/1 end
+7
source

Source: https://habr.com/ru/post/1629044/


All Articles