【问题标题】:Elixir: pipe more then one variable into a functionElixir:将多个变量传递给函数
【发布时间】:2017-06-28 18:47:22
【问题描述】:

Elixir 可以将输入通过管道传输到函数中,这使得代码更容易阅读。

比如这样的

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

将字符串sentence 传递到String.split 的第一个参数中。

现在考虑我还想将第二个参数传递给String.split。 Elixir 有可能做到这一点吗?我的意思是这样的:

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

谢谢!

【问题讨论】:

  • 不,这种语法只适用于一个参数。
  • 你可以通过管道传递一个元组列表——第一个元组包含你想要的任何参数。如果有帮助的话。

标签: functional-programming pipe elixir


【解决方案1】:

正如@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"]

【讨论】:

  • 为什么不只是params ++ args 而不是List.foldr(params, args, &List.insert_at(&2, 0, &1))
  • @Dogbert 演示该方法。基本上,调整这段代码很容易将参数嵌入到 args 的任何所需位置。对于相反的顺序,可以使用List.foldl/3 等。对于最简单的情况,++ 当然可以。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-21
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多