在Elm中,约简函数称为“折叠”,有两种标准的方法可将值“向上”折叠:从左侧开始,foldl从右侧开始foldr。
>List.foldl(+) 0 [1,2,3] 6 : number
到的参数foldl和foldr有:
降低功能:newValue -> accumulator -> accumulator
累加器初始值
减少清单
自定义功能的另一个示例:
type alias Counts = { odd : Int , even : Int } addCount : Int -> Counts -> Counts addCount num counts = let (incOdd, incEven) = if num `rem` 2 == 0 then (0,1) else (1,0) in { counts | odd =counts.odd+ incOdd , even =counts.even+ incEven } > List.foldl addCount { odd = 0, even = 0 } [1,2,3,4,5] { odd = 3, even = 2 } : Counts
在上面的第一个示例中,程序如下所示:
List.foldl (+) 0 [1,2,3] 3 + (2 + (1 + 0)) 3 + (2 + 1) 3 + 3 6
List.foldr (+) 0 [1,2,3] 1 + (2 + (3 + 0)) 1 + (2 + 3) 1 + 5 6
对于像(+)这样的交换函数,实际上并没有什么区别。
但是看看会发生什么(::):
List.foldl (::) [] [1,2,3] 3 :: (2 :: (1 :: [])) 3 :: (2 :: [1]) 3 :: [2,1] [3,2,1]
List.foldr (::) [] [1,2,3] 1 :: (2 :: (3 :: [])) 1 :: (2 :: [3]) 1 :: [2,3] [1,2,3]