我必须制作一个2D列表[[Int]].[Int]在Haskell中的一维列表中.
该函数应采用args"r"Int表示行数和1D列表,应将其切成长度为"r"的行.
如果列表的长度超过r*r,则应删除列表的其余部分.Howerver如果列表的长度小于r*r,那么缺失的元素应该作为0插入列表中.
例1:
输入:r = 2
list = [1,2,3,4,5,6]
输出:[[1,2],[3,4]]
例2:
输入:r = 3
list = [1,2,3,4,5,6]
输出:[[1,2,3],[4,5,6],[0,0,0]]
所以我的方法是关于thre函数如下:
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) ) )))
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我无法理解,为什么它不起作用zeroList r myList.返回一个普通的列表.
有人可以帮帮我吗?
我不得不承认我不理解你是怎么做的.所有这些if then else都非常糟糕.:-)另外,由于Haskell的惰性评估和无限列表,没有必要事先计算所需的零的确切数量.
草稿如何可以做到:
make2DList r l = take r . chunks r $ l ++ zeroes
where
zeroes = [0,0..]
chunks r xs = take r xs : chunks r (drop r xs)
Run Code Online (Sandbox Code Playgroud)
说明:
chunks将任何列表拆分为给定长度的块的函数.chunks填充列表.