丢失的折叠

时间:2017-07-02 08:54:39

标签: haskell recursion fold language-features haskell-prelude

如果要折叠列表,我会看到四种方法。

从列表右侧折叠,右侧是递归术语

  

foldrr( - )100 [1..10] = 1 - (2 - (3 - (4 - (5 - (6 - (7 - (8 - (9 - (10 - (100)))) )))))))= 95

foldrr :: (a -> b -> b) -> b -> [a] -> b
foldrr step zero (x:xs) = step x (foldrr step zero xs)
foldrr _    zero []     = zero

从列表右侧折叠,左侧是递归术语

  

foldrl( - )100 [1..10] =((((((((((100) - 10) - 9) - 8) - 7) - 6) - 5) - 4) - 3 ) - 2) - 1 = 45

foldrl :: (a -> b -> a) -> a -> [b] -> a
foldrl step zero (x:xs) = step (foldrl step zero xs) x
foldrl _    zero []     = zero

从列表左侧折叠,右侧是递归术语

  

foldlr( - )100 [1..10] = 10 - (9 - (8 - (7 - (6 - (5 - (4 - (3 - (2 - (1 - (100)))) )))))))= 105

foldlr :: (a -> b -> b) -> b -> [a] -> b
foldlr step zero (x:xs) = foldlr step (step x zero) xs
foldlr _    zero []     = zero

从列表左侧折叠,左侧是递归术语

  

foldll( - )100 [1..10] =((((((((((100) - 1) - 2) - 3) - 4) - 5) - 6) - 7) - 8 ) - 9) - 10 = 45

foldll :: (a -> b -> a) -> a -> [b] -> a
foldll step zero (x:xs) = foldll step (step zero x) xs
foldll _    zero []     = zero

这些折叠中只有两个使其成为Prelude foldrfoldl。有没有理由只包括两个折叠,为什么这两个?

1 个答案:

答案 0 :(得分:17)

foldrlfoldlr不会添加任何表现力:它们与其他两个折叠相同,但折叠功能会翻转。

foldrl f = foldr (flip f)
foldlr f = foldl (flip f)

-- Or this, if you prefer
foldrl = foldr . flip
foldlr = foldl . flip

但是用foldl来定义foldr并不是那么容易,所以提供它们都很有用。