Elm中应用函数列表转换值的最惯用方法是什么?
在Elm中应用一组变换函数的惯用写法
你觉得(\f acc -> f acc)这段代码冗余是对的,Elm里有几种更简洁且符合惯用风格的写法:
1. 直接使用函数应用运算符<|
你的lambda本质上就是把列表中的函数应用到累积值上,这正好是<|运算符的作用(它接受一个函数和一个参数,返回函数应用的结果)。所以可以直接替换掉冗余的lambda:
let transformations = [ String.replace "dogs" "cats" , String.replace "bark" "purr" ] str = "dogs are the best, they bark" in List.foldl (<|) str transformations
2. 先组合变换函数,再统一应用
另一种更具声明性的方式是把所有变换函数组合成一个单一的函数,再一次性应用到初始值上。这里可以用函数组合运算符配合foldl或foldr:
用foldl和<<(左组合)
let transformations = [ String.replace "dogs" "cats" , String.replace "bark" "purr" ] str = "dogs are the best, they bark" combinedTransform = List.foldl (<<) identity transformations in combinedTransform str
用foldr和>>(右组合)
let transformations = [ String.replace "dogs" "cats" , String.replace "bark" "purr" ] str = "dogs are the best, they bark" combinedTransform = List.foldr (>>) identity transformations in combinedTransform str
这两种组合方式和你原来的代码效果完全一致:先执行第一个变换,再执行第二个变换。这里的identity是恒等函数(identity x = x),作为组合的初始值,确保变换列表为空时也能正常返回初始值。
<<表示“先执行右侧函数,再执行左侧函数”,即f << g = \x -> f(g(x))>>表示“先执行左侧函数,再执行右侧函数”,即f >> g = \x -> g(f(x))
这两种写法都比原lambda更简洁,也更贴合Elm强调函数组合的风格,尤其是组合函数的方式能更清晰地表达“串联一系列变换”的意图。
内容的提问来源于stack exchange,提问作者sba
相关产品推荐
相关产品推荐

