3
votes

I'm new to haskell and was trying to write a function to generate a powerset which only includes consecutive subsets eg: [1,2,3] -> [[],[1],[2],[3],[1,2],[2,3],[1,2,3]]

I found this on a blog http://davidtran.doublegifts.com/blog/?p=7

powerset :: [a] -> [[a]]
powerset []     = [[]]
powerset (x:xs) = powerset xs ++ map (x:) (powerset xs)
-- powerset (x:xs) = powerset xs ++ [x:xs' | xs' <- powerset xs]

but this generates all the subsets i.e [1,3] included which i dont want? is there anyway to fix this code to work or do I have to rethink my approach. Also i do not want to use built in library functions, wanna get my basics right.

2
What do you mean by 'consecutive subsets'? - yatima2975
i mean [1,2] [2,3] but not [1,3] - NyaniOS
As a matter of terminology: I usually see people use the term substring to refer to the "consecutive subsets" and the term subsequence for the not necessarily consecutive subsets. - hugomg
@missingno: That makes perfect sense! I somehow had the (silly) idea that the subsets themselves must be consecutive (or that you could get from [1,2] to [2,3] by 'adding 1'), not the elements they contain. - yatima2975

2 Answers

12
votes

Something like

conseqPower = ([] :) . concatMap (tail . inits) . tails
0
votes

Filter out the non-"consecutive" lists.