我们可以将所有剩余的
inits
数据都添加到前面,例如:
inits' :: [a] -> [[a]]
inits' [] = [[]]
inits' (x:xs) = [] : <b>map (x:) (</b>inits' xs<b>)</b>
作为基本情况,当输入为空列表时,我们返回一个包含空列表的单例列表。
在递归情况下,我们首先生成空列表,然后是列表尾部的inits',但所有这些元素都被x前置(使用map (x:))。
然后我们有:
Prelude> inits' [1,4,2,5]
[[],[1],[1,4],[1,4,2],[1,4,2,5]]
鉴于以下原因(非按照评估顺序排列):
inits' [1,4,2,5]
-> [] : map (1:) (inits' [4,2,5])
-> [] : map (1:) ([] : map (4:) (inits' [2,5]))
-> [] : map (1:) ([] : map (4:) ([] : map (2:) (inits' [5])))
-> [] : map (1:) ([] : map (4:) ([] : map (2:) ([] : map (5:) (inits' []))))
-> [] : map (1:) ([] : map (4:) ([] : map (2:) ([] : map (5:) [[]])))
-> [] : map (1:) ([] : map (4:) ([] : map (2:) ([] : [[5]])))
-> [] : map (1:) ([] : map (4:) ([] : map (2:) [[],[5]]))
-> [] : map (1:) ([] : map (4:) ([] : [[2],[2,5]]))
-> [] : map (1:) ([] : map (4:) [[],[2],[2,5]])
-> [] : map (1:) ([] : [[4],[4,2],[4,2,5]])
-> [] : map (1:) [[],[4],[4,2],[4,2,5]]
-> [] : [[1],[1,4],[1,4,2],[1,4,2,5]]
-> [[],[1],[1,4],[1,4,2],[1,4,2,5]]
inits
版本。 - RoadRunner(((a:) . (b:)) . (c:)) . (d:) $ []
的元素。在揭示它的头之前,这需要重新关联。因此,如果你做类似于map headMay (inits xs)
的事情,我预计你会遇到麻烦。 - dfeueri
是原始列表中的索引)。实际上,运行head $ (map ($[]) . scanl (\a x-> a . (x:)) id) [1..] !! 300000
,然后再运行3000000
,运行时间比为10.0。(参见此处) - Will Nessmap headMay $ zipWith (\_ i -> take i xs) xs [0..]
不会,确实不错。很好。 - Will Ness