Ampersand and functions in Elixir

Published September 28, 2018 by Toran Billups

In part 5 of my Elixir journey I wanted to share a little about the `&` operator you see often.


Functions are at the center of almost everything in Elixir so you might be asking yourself "does a short(er) syntax exist to create them?". Take the anonymous function below that adds `2` to any number you pass it.

    add_two = fn (a) -> a + 2 end

As luck would have it, the `&` operator in Elixir allows us to write the same function in a more concise syntax.

    add_two = &(&1 + 2)

The `&1` placeholder you see inside the parentheses represents the first parameter to the function. I find the `&` operator used frequently when using the Enum module like you see below.

    list = [1, 2, 3]
    # verbose, fn (e) -> e + 1 end)
    # concise, &(&1 + 1))

Another use of the `&` operator is that it allows you to create an anonymous function that acts like an alias.

    list = [1, 2, 3]
    # traditional count
    # count with alias
    len = &Enum.count/1

In the example above I've created a variable `len` that holds a new function for `Enum.count` so we can call it without the full `Module.function` path.

I'll admit this syntax was fairly terse and confusing when I first started learning Elixir. As I spend more time with the language and ecosystem I've found this both useful and intuitive.

Twitter / Github / Email