因此,使用foldr
从右侧折叠列表的直觉(这不是递归定义),您可以在简单的情况下得到以下结果:
foldr (+) 1 [2,3,4]
foldr (+) (4 + 1) [2,3]
foldr (+) (3 + 4 + 1) [2]
foldr (+) (2 + 3 + 4 + 1) []
(2 + 3 + 4 + 1)
10
让我们在您的示例中做同样的事情并考虑初始元素repeat [] == [[],[],[],[], …]
foldr (zipWith (:)) ([[],[],[],[], ...]) [[1,2,3],[4,5,6],[7,8,9,10]]
foldr (zipWith (:)) (zipWith (:) [7,8,9,10] [[],[],[],[], ...]) [[1,2,3],[4,5,6]]
等一下。让我们发展zipWith (:) [7,8,9,10] [[],[],[],[], ...]
zipWith (:) [7,8,9,10] [[],[],[],[], ...] -- apply the funciton (:) pairwise
[7:[], 8:[], 9:[], 10:[]] -- we get rid of the infinite list at this point.
[[7],[8],[9],[10]]
从这里我们可以轻松地跟踪其余的代码
foldr (zipWith (:)) ([[],[],[],[], ...]) [[1,2,3],[4,5,6],[7,8,9,10]]
foldr (zipWith (:)) (zipWith (:) [7,8,9,10] [[],[],[],[], ...]) [[1,2,3],[4,5,6]]
foldr (zipWith (:)) ([[7],[8],[9],[10]]) [[1,2,3],[4,5,6]]
foldr (zipWith (:)) (zipWith (:) [4,5,6] [[7],[8],[9],[10]]) [[1,2,3]]
foldr (zipWith (:)) (zipWith (:) [1,2,3] [[4:7],[5:8],[6:9]) []
zipWith (:) [1,2,3] [[4:7],[5:8],[6:9]
[[1,4,7],[2,5,8],[3,6,9]]
请注意,这不是正确的定义,foldr
我们正在立即评估结果而不是懒惰地评估结果(就像 haskell 所做的那样),但这只是为了理解。