简体   繁体   English

Elixir:将多个变量传递给一个函数

[英]Elixir: pipe more then one variable into a function

Elixir has the possibility to pipe input into a function, which makes code more readable very often. Elixir可以通过管道将输入传递到函数中,这使得代码更易于阅读。

For example something like this 例如这样的事情

sentence  |> String.split(@wordSplitter, trim: true)

which pipes the String sentence into the first argument of String.split . 它将String sentence通过管道String.splitString.split的第一个参数中。

Now consider I would also like to pipe the second argument into String.split . 现在考虑我还想将第二个参数传递给String.split Is there a possibility to do that in Elixir? 有可能在Elixir中这样做吗? I mean something like this: 我的意思是这样的:

sentence, @wordSplitter |> String.split(trim: true)

Thanks! 谢谢!

As @Dogbert pointed out, this is impossible out of the box. 正如@Dogbert指出的那样,这是不可能的。 The helper is pretty straightforward, though: 但是,该助手非常简单:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM