foldr 相似
這是正確摺疊的實現方式:
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f z [] = z
foldr f z (x:xs) = f x (foldr f z xs) -- = x `f` foldr f z xs
右側摺疊 foldr
與右側相關聯。那是:
foldr (+) 0 [1, 2, 3] -- is equivalent to 1 + (2 + (3 + 0))
其原因是,被 foldr
像這樣進行評估(看 foldr
的感應步驟):
foldr (+) 0 [1, 2, 3] -- foldr (+) 0 [1,2,3]
(+) 1 (foldr (+) 0 [2, 3]) -- 1 + foldr (+) 0 [2,3]
(+) 1 ((+) 2 (foldr (+) 0 [3])) -- 1 + (2 + foldr (+) 0 [3])
(+) 1 ((+) 2 ((+) 3 (foldr (+) 0 []))) -- 1 + (2 + (3 + foldr (+) 0 []))
(+) 1 ((+) 2 ((+) 3 0)) -- 1 + (2 + (3 + 0 ))
最後一行相當於 1 + (2 + (3 + 0))
,因為 ((+) 3 0)
是一樣的 (3 + 0)
。