Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Elixir 如何使用管道操作符将参数传递给匿名函数?_Elixir - Fatal编程技术网

Elixir 如何使用管道操作符将参数传递给匿名函数?

Elixir 如何使用管道操作符将参数传递给匿名函数?,elixir,Elixir,我在玩长生不老药。只是想知道是否可以使用pipe|>操作符将参数传递给匿名函数。这就是我的意思 a = [1,2,3] #=> [1,2,3] m = fn ([h|t]) -> [ h*h | m.(t) ] end #=> head squared and call m with tail. Not sure how to use & shortcut for this. m.(a) #=> [1,4,9] a |> m #=> undefine

我在玩长生不老药。只是想知道是否可以使用pipe
|>
操作符将参数传递给匿名函数。这就是我的意思

a = [1,2,3] #=> [1,2,3]
m = fn ([h|t]) -> [ h*h | m.(t) ] end #=> head squared and call m with tail.  Not sure how to use & shortcut for this.
m.(a) #=> [1,4,9]
a |> m #=> undefined function m/1 (understood. Arity is 1)
a |> m.(&1) #=> unhandled &1 outside of capture

该错误是由于基本条件导致的,在该条件下没有参数,因此无法将其划分为[H | T]

a = [1,2,3] #=> [1,2,3]
m = fn
  ([],_) -> []
([h|t], fun) -> [ h*h | fun.(t, fun)]
end

b = m.(a,m)

IO.inspect b #=> [1, 4, 9]
更新


另一个区别是函数本身是未知的,因此需要将其作为参数(fun)传递。

该错误是由于基本条件导致的,在该条件下,没有参数剩余,无法将其划分为[H | T]

a = [1,2,3] #=> [1,2,3]
m = fn
  ([],_) -> []
([h|t], fun) -> [ h*h | fun.(t, fun)]
end

b = m.(a,m)

IO.inspect b #=> [1, 4, 9]
更新


另一个区别是函数本身是未知的,因此需要将其作为参数传递(fun)。

您可以将匿名函数传递给管道,例如

 m = fn(x) -> x * x end # Function<6.50752066/1 in :erl_eval.expr/5>
 3 |> m.() # 9 

您可以将匿名函数传递给管道,例如

 m = fn(x) -> x * x end # Function<6.50752066/1 in :erl_eval.expr/5>
 3 |> m.() # 9 
也许是这样

a |> (&m.(&1))
也许是这样

a |> (&m.(&1))
m=fn([h | t])->[h*h | m(t)]
将给出一个错误
m=fn([h | t])->[h*h | m(t)]
将给出一个错误