Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

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

For example, I need a function:

gather :: Int -> [a] -> [[a]]
gather n list = ???

where gather 3 "Hello!" == ["Hel","ell","llo","ol!"].

I have a working implementation:

gather :: Int-> [a] -> [[a]]
gather n list = 
    unfoldr 
        (x -> 
            if fst x + n > length (snd x) then 
                Nothing 
            else 
                Just 
                    (take 
                        n 
                        (drop 
                            (fst x)
                            (snd x)), 
                    (fst x + 1, snd x))) 
        (0, list)

but I am wondering if there is something already built into the language for this? I scanned Data.List but didn't see anything.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...