如果要折叠列表,我会看到四种方法。
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 foldr
和foldl
。有没有理由只包括两个折叠,为什么这两个?
答案 0 :(得分:17)
foldrl
和foldlr
不会添加任何表现力:它们与其他两个折叠相同,但折叠功能会翻转。
foldrl f = foldr (flip f)
foldlr f = foldl (flip f)
-- Or this, if you prefer
foldrl = foldr . flip
foldlr = foldl . flip
但是用foldl
来定义foldr
并不是那么容易,所以提供它们都很有用。