为什么haskell中的列表理解不包括大小的列表< ñ

时间:2016-02-06 15:03:35

标签: haskell list-comprehension

我正在查看此代码以在Haskell中生成组合

combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations n xs = [ xs !! i : x | i <- [0..(length xs)-1] 
                                  , x <- combinations (n-1) (drop (i+1) xs) ]

我试图想象树如何扩展,但我不明白为什么列表不包含红色的路径。

enter image description here

combinations 3 "abcd"
["abc","abd","acd","bcd"]

我所能看到的只是xs !! i : x,即将第i个元素附加到它的尾部的n-1个组合中,但为什么不包括[d] : [[]] = [d]

2 个答案:

答案 0 :(得分:4)

你要做的是:“隔离”列表中的每个元素与其余元素,然后递归其余元素。您尝试通过选择每个元素login.defs来实现此分离,而另一方面删除。但这不是!!所做的,而是drop的任务。但是,使用索引很难:

deleteBy

通常索引到Haskell列表是相当单一的。更好的方法是通过直接递归来实现这种隔离:

combinations n xs = [ xs !! i : x | i <- [0..(length xs)-1] 
                                  , x <- combinations (n-1) (xs' i) ]
 where xs' i = snd <$> deleteBy ((==i).fst) (zip [0..] xs)

然后你可以做

foci :: [a] -> [(a,[a])]
foci [] = []
foci (x:xs) = (x,xs) : map (second (x:)) (foci xs)

答案 1 :(得分:1)

drop (i+1) xs不会删除i+1元素,而是删除索引为< i+1的所有元素。