Elixir:减少函数列表中的枚举

Elixir : reduce enum over list of functions

我刚刚写了:

def transform(list_of_functions, elem) do
  Enum.reduce(list_of_functions, elem, fn func, res when is_function(func) -> func.(res) end)
end

被称为:

transform([
  &(2*&1),
  fn x -> x % 3 end,
  &Integer.to_string/1
], 5) # "1"

但感觉太初级了,我想知道 Elixir 本身是否存在这样的功能。我本以为 Enum.transform/2 但它不存在。 :( 它有另一个名字吗?

这是 . We usually use pipe operator |> 中的 counter-idiomatic。

旁注: % 不是执行模除法的运算符,顺便说一句,rem/2 是。

5
|> Kernel.*(2)
|> rem(3)
|> Integer.to_string()
#⇒ "1"

当然,如果需要,可以写成foldl符号。

Enum.reduce([
  &(2*&1),
  &rem(&1, 3),
  &Integer.to_string/1
], 5, & &2 |> &1.()) 
#⇒ "1"

但是,elixir 仍然不是 haskell,携带函数不是编写惯用代码的方式。