作为左折叠实现的列表串联的性能



考虑将列表串联实现为左折叠,即foldl (++) []。 在惰性求值语言(如 Haskell(中,此实现的复杂性有多大? 我知道在严格的语言中,性能在元素总数中是二次的,但是当涉及懒惰时会发生什么?

我试图手动评估表达式([1,2,3] ++ [4,5,6]) ++ [7,8,9](对应于foldl (++) [] [[1,2,3], [4,5,6], [7,8,9]]似乎我们只遍历每个元素一次,但我不确定我的推理是否正确:

([1,2,3] ++ [4,5,6]) ++ [7,8,9]
= { rewrite expression in prefix notation }
(++) ((++) [1,2,3] [4,5,6]) [7,8,9]
= { the first (++) operation needs to pattern match on its first argument; so it evaluates the first argument, which pattern matches on [1,2,3] }
(++) (case [1,2,3] of {[] -> [4,5,6]; x:xs' -> x:(++) xs' [4,5,6]}) [7,8,9]
= { x = 1, xs' = [2,3] }
(++) (1:(++) [2,3] [4,5,6]) [7,8,9]
= { the first (++) operation can now pattern match on its first argument }
1:([2,3] ++ [4,5,6]) ++ [7,8,9]

我假设以下(++)实现:

(++) :: [a] -> [a] -> [a]
xs ++ ys = case xs of [] -> ys
(x:xs') -> x : (xs' ++ ys)

假设我们有([1,2,3]++[4,5,6])++[7,8,9]

([1,2,3]++[4,5,6])++[7,8,9]
(1:([2,3]++[4,5,6))++[7,8,9]
1:(([2,3]++[4,5,6])++[7,8,9])
1:((2:([3]++[4,5,6])++[7,8,9])
1:2:(([3]++[4,5,6])++[7,8,9])
1:2:(3:([]++[4,5,6])++[7,8,9])
1:2:3:(([]++[4,5,6])++[7,8,9])
1:2:3:([4,5,6]++[7,8,9])
1:2:3:4:([5,6] ++ [7,8,9])
1:2:3:4:5:([6] ++ [7,8,9])
1:2:3:4:5:6:([] ++ [7,8,9])
1:2:3:4:5:6:[7,8,9]
[1,2,3,4,5,6,7,8,9]

注意到第一个列表中的每个元素必须移动两次吗?那是因为从最后开始就是两个。一般来说,如果我们(((a1++a2)++a3)++..an)列表中的每个元素ai则必须移动n-i次。

所以,如果你想要整个列表,它是二次的。如果你想要第一个元素,并且你有n列表,它是n-1* 操作(我们需要做++n次的步进情况(。如果你想要第i个元素,它是它之前所有元素的操作数,加上k-1,它在第k个列表中,从末尾开始计算。

*加上foldl本身的n操作,如果我们想变得迂腐

最新更新