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 of parameters. For example, say we define our square/1
function as pow/1
instead where, if pow
is given one function, it assumes we want to raise the argument to the second power, otherwise, there is a pow/2
that takes the base and the...