Haskell:将100个数字的列表更改为10个10个数字的列表?

时间:2014-06-16 20:23:26

标签: list function haskell functional-programming purely-functional

在Haskell中,如何将x数列表更改为n个n个数列?

第一个子列表的编号从第一到第十,第二个列表从第11到第20 ......

myFunction :: [Int] - > [[INT]]

2 个答案:

答案 0 :(得分:5)

Data.List.Split中有chunksOf个功能:

chunksOf 2 [0, 1, 2, 3] -- [[0, 1], [2, 3]]

或者,我们splitAtpreludechunksOf可以轻松实现:

chunksOf :: Int -> [a] -> [[a]]
chunksOf n [] = []
chunksOf n xs = let (as, bs) = splitAt n xs in as : chunksOf n bs

答案 1 :(得分:3)

使用take and drop可能会更简单一点,并且不需要库。

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf n xs = take n xs : chunksOf n (drop n xs)
相关问题