Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell consecutive sublist of list

Tags:

list

haskell

Hi I have this little function which finds the powerset of set but i need all the consecutive sublist. [1,2,3] -> [[],[1],[2],[3],[1,2],[2,3],[1,2,3]] and not [[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]

Is there a way to fix this function to do what i want?

sublists :: [a] -> [[a]]
sublists [] = [[]]
sublists (x:xs) = sublists xs ++ map (x:) (sublists xs)  
like image 556
Laci Feldsam Avatar asked Mar 07 '18 12:03

Laci Feldsam


2 Answers

It's not exactly elegant, but you can use divvy from Data.List.Split:

xs = [1,2,3]
[] : concat [ divvy n 1 xs | n <- [1..length xs] ]
-- [[],[1],[2],[3],[1,2],[2,3],[1,2,3]]
like image 137
Michael Kohl Avatar answered Oct 16 '22 18:10

Michael Kohl


The answer by Michael Kohl is not buildable.
Divvy is already returning [[a]] so the list comprehension is returning [[[a]]]. I would just add a comment, but not enough reputation to do that. Use concat.

sublists xs = [] : concat [ divvy n 1 xs | n <- [1..length xs]]
like image 2
Anicka Burova Avatar answered Oct 16 '22 16:10

Anicka Burova