Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a module function inside Enum.map without getting an "Undefined reference" error?

Tags:

elixir

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?

like image 796
Frank Schmitt Avatar asked Feb 01 '15 19:02

Frank Schmitt


1 Answers

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.

like image 146
whatyouhide Avatar answered Nov 07 '22 17:11

whatyouhide