药剂:减少功能列表中的枚举

问题描述

我刚刚写道:

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,但是它不存在。 :(它有别的名字吗?

解决方法

这在中是惯用语。我们通常为此使用管道运算符|>

边注: %不是执行模除的运算符,顺便说一句,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"

但是,长生不老药不是haskell,带有功能并不是编写惯用代码的方式。