开发者

Splitting list into n-tuples [duplicate]

This question already has answers here: Gro开发者_开发技巧uping a list into lists of n elements in Haskell (4 answers) Closed 5 years ago.

How can I split a list into list of tuples/lists of specified length? splitBy :: Int -> [a] -> [[a]]

splitBy 2 "asdfgh" should return ["as", "df", "gh"]


splitEvery usually gets the nod for this job.


Searching Hoogle for Int -> [a] -> [[a]] yields chunksOf, which may be of use.


One way of doing it:

splitBy :: Int -> [a] -> [[a]]
splitBy _ [] = []
splitBy n xs = take n xs : splitBy n (drop n xs)

Another way of doing it:

splitBy' :: Int -> [a] -> [[a]]
splitBy' _ [] = []
splitBy' n xs = fst split : splitBy' n (snd split)
                where split = splitAt n xs
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜