我必须制作一个 2D 列表[[Int]]
。[Int]
在 Haskell的一维列表中。
该函数应采用 args "r" Int 指示行数和一维列表,应将其切成长度为 "r" 的行。
如果列表的长度比 r*r 长,则应删除列表的其余部分。但是如果列表的长度比 r*r 短,那么缺失的元素应该作为 0 插入到列表中。
示例 1:
输入:r = 2
列表 = [1,2,3,4,5,6]
输出:[[1,2],[3,4]]
示例 2:
输入:r = 3
列表 = [1,2,3,4,5,6]
输出:[[1,2,3],[4,5,6],[0,0,0]]
所以我的方法是通过以下功能:
zeroList :: Int -> [Int] -> [Int]
zeroList r myList = (take (r*r-(length myList)) (0 : zeroList r myList))
processList :: Int -> [Int] -> [[Int]]
processList r myList = (if (length myList < r*r)
then (myList:(zeroList r myList))
else if (length (myList > r*r))
then (reverse (drop r (reverse myList)))
else
myList)
make2DList :: Int -> [Int] -> [[Int]]
make2DList r myList = (if myList == []
then make2DList
else ( ( take r (processList r myList) ):( make2DList r ( drop r (processList r myList) ) )))
zeroList 函数正常工作,但其他两个函数不工作。我有一些编译错误信息:
D:\haskell\task1.hs:6:63:
Couldn't match expected type `[Int]' with actual type `Int'
Expected type: [[Int]]
Actual type: [Int]
In the return type of a call of `zeroList'
In the second argument of `(:)', namely `(zeroList r myList)'
D:\haskell\task1.hs:14:54:
Couldn't match expected type `[[Int]]'
with actual type `Int -> [Int] -> [[Int]]'
In the expression: make2DList
In the expression:
(if myList == [] then
make2DList
else
((take r myList) : (make2DList r (drop r myList))))
In an equation for `make2DList':
make2DList r myList
= (if myList == [] then
make2DList
else
((take r myList) : (make2DList r (drop r myList))))
Failed, modules loaded: none.
Prelude>
我无法理解,为什么它不起作用zeroList r myList
。返回一个普通列表。
有人可以帮我吗?