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)
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]]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With