O'Reilly logo

Learning Elixir by Kenny Ballou

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Grabbing functions

Elixir supports passing defined functions as parameters. That is, Elixir's functions are first-class citizens of the type system. But then, how do we pass the existing functions around? We use the & operator or function capture operator . Going back to our MyMath.square/1 function, we could pass it to Enum.map/2 with the following:

iex(1)> import_file("mymath.exs")
...
iex(2)> Enum.map([1, 2, 3], &MyMath.square/1)
[1, 4, 9]

Here, we load the module again, for completeness, and then we invoke Enum.map/2 with the list [1, 2, 3] and pass our square/1 function from MyMath. You may wonder why we need to grab the function with the arity. This, if you recall, is because Elixir functions are defined by their name and arity or number ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required