我正在查看此代码以在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) ]
我试图想象树如何扩展,但我不明白为什么列表不包含红色的路径。
combinations 3 "abcd"
["abc","abd","acd","bcd"]
我所能看到的只是xs !! i : x
,即将第i个元素附加到它的尾部的n-1个组合中,但为什么不包括[d] : [[]] = [d]
。
答案 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
的所有元素。