Elixir匿名函数

示例

在Elixir中,一种常见的做法是使用匿名函数。创建匿名函数很简单:

iex(1)> my_func = fn x -> x * 2 end
#Function<6.52032458/1 in :erl_eval.expr/5>

通用语法为:

fn args -> output end

为了便于阅读,您可以在参数周围加上括号:

iex(2)> my_func = fn (x, y) -> x*y end
#Function<12.52032458/2 in :erl_eval.expr/5>

要调用匿名函数,请按分配的名称进行调用,然后.在名称和参数之间添加。

iex(3)>my_func.(7, 5)
35

可以声明不带参数的匿名函数:

iex(4)> my_func2 = fn ->IO.puts"hello there" end
iex(5)> my_func2.()
hello there
:ok

使用捕获运算符

为了使匿名函数更简洁,可以使用捕获运算符 &。例如,代替:

iex(5)> my_func = fn (x) -> x*x*x end

你可以写:

iex(6)> my_func = &(&1*&1*&1)

对于多个参数,请使用与每个参数相对应的数字,从开始1:

iex(7)> my_func = fn (x, y) -> x + y end

iex(8)> my_func = &(&1 + &2)   # &1 stands for x and &2 stands for y

iex(9)> my_func.(4, 5)
9

多体

匿名函数也可以具有多个主体(作为模式匹配的结果):

my_func = fn
  param1 -> do_this
  param2 -> do_that
end

当您调用具有多个主体的函数时,Elixir会尝试匹配适当函数主体提供的参数。