Is there a built-in function to get all consecutive subsequences of size n of a list in Haskell?

You could use tails:

gather n l = filter ((== n) . length) $ map (take n) $ tails l

or using takeWhile instead of filter:

gather n l = takeWhile ((== n) . length) $ map (take n) $ tails l

EDIT: You can remove the filter step by dropping the last n elements of the list returned from tails as suggested in the comments:

gather n = map (take n) . dropLast n . tails
  where dropLast n xs = zipWith const xs (drop n xs)

Leave a Comment