softshipper
softshipper

Reputation: 34071

Why Is The Elixir Capture Operator Needed To Bind A Function To A Value

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?

Upvotes: 5

Views: 698

Answers (1)

zaboco
zaboco

Reputation: 2838

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

Upvotes: 8

Related Questions