I have a simple module containing a single function:
defmodule Funcs do
def double(x) do
x*2
end
end
When I start iex
with the file name as argument, I can call the function just fine:
iex(5)> Funcs.double(3)
6
But when I try to use it in Enum.map
, I get an undefined function
error:
iex(2)> Enum.map([1,2,3,4], Funcs.double)
** (UndefinedFunctionError) undefined function: Funcs.double/0
Funcs.double()
whereas if I just use an analogous anonymous function, everything works as expected:
iex(6)> Enum.map([1,2,3,4], fn(x) -> x*2; end)
[2, 4, 6, 8]
How can I use a module function (unsure whether that's the correct term) as an argument to Enum.map?
The syntax for capturing non-anonymous functions uses &function/arity
.
In your example:
Enum.map([1,2,3,4], &Funcs.double/1)
You can read more about the capture syntax (which is very common in Elixir) in the docs for the &
special form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With