Why doesn't this list comprehension in haskell include lists of size < n -


i looking @ code generating combinations in haskell

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

i tried visualize how tree gets expanded, not understand why list doesn't include paths in red.

enter image description here

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

all can see xs !! : x ie append i'th element n -1 combinations of it's tail, why doesn't [d] : [[]] = [d] included.

what you're trying this: “isolate” each element in list rest, recurse on rest. attempt achieve seperation by, on 1 side, selecting each element !!, , on other removing it. that's not quite drop does, it's rather task deleteby. awkward use indices, though:

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

in general it's rather unidiomatic index haskell lists. better approach implement isolation-thing direct recursion:

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

and can do

combinations n xs = [ x₀ : xs'' | (x₀,xs') <- foci xs                                 , xs'' <- combinations (n-1) xs' ] 

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -