Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...