[英]Is it possible to choose where the pipe output is inserted into Elixir function args?
[英]Elixir: pipe more then one variable into a function
Elixir可以通过管道将输入传递到函数中,这使得代码更易于阅读。
例如这样的事情
sentence |> String.split(@wordSplitter, trim: true)
它将String sentence
通过管道String.split
到String.split
的第一个参数中。
现在考虑我还想将第二个参数传递给String.split
。 有可能在Elixir中这样做吗? 我的意思是这样的:
sentence, @wordSplitter |> String.split(trim: true)
谢谢!
正如@Dogbert指出的那样,这是不可能的。 但是,该助手非常简单:
defmodule MultiApplier do
def pipe(params, mod, fun, args \\ []) do
apply(mod, fun, List.foldr(params, args, &List.insert_at(&2, 0, &1)))
end
end
iex> ["a b c", " "]
...> |> MultiApplier.pipe(String, :split, [[trim: true]])
#⇒ ["a", "b", "c"]
iex> ["a b c", " ", [trim: true]]
...> |> MultiApplier.pipe(String, :split, [])
#⇒ ["a", "b", "c"]
iex> ["a b c"]
...> |> MultiApplier.pipe(String, :split, [" ", [trim: true]])
#⇒ ["a", "b", "c"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.