Splitting list into n-tuples [duplicate]

南笙酒味 提交于 2019-12-31 03:12:15

问题


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"]


回答1:


splitEvery usually gets the nod for this job.




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/5819649/splitting-list-into-n-tuples

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!