当前位置: 动力学知识库 > 问答 > 编程问答 >

haskell - Splitting list into n-tuples

问题描述:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: