如何将列表拆分为指定长度的元组/列表列表? splitBy :: Int - > [a] - > [[α]]
splitBy 2“asdfgh”应该返回[“as”,“df”,“gh”]
答案 0 :(得分:6)
splitEvery
通常会得到这份工作的认可。
答案 1 :(得分:3)
答案 2 :(得分:2)
一种方法:
splitBy :: Int -> [a] -> [[a]]
splitBy _ [] = []
splitBy n xs = take n xs : splitBy n (drop n xs)
另一种方法:
splitBy' :: Int -> [a] -> [[a]]
splitBy' _ [] = []
splitBy' n xs = fst split : splitBy' n (snd split)
where split = splitAt n xs