【发布时间】:2014-12-31 01:31:15
【问题描述】:
我正在编写一个函数来修改下面给出的给定二维“数组”的元素:
change_elem :: Int -> Int -> a -> [[a]] -> [[a]]
-- empty list case
change_elem _ _ _ [] = []
-- have arrived at the element to change`
change_elem 0 0 x ((y:ys):ls) = (x:ys):ls
-- reduce the column until we find the element to change
change_elem 0 col x ((y:ys):ls) = [[y]] ++ change_elem 0 (col-1) x (ys:ls)
-- reduce the row until we find the column to change
change_elem row col x (l:ls) = l : change_elem (row-1) col x ls
它适用于change_elem 1 0 3 [[1,2],[4,5]] 等输入并产生[[1,2],[3,5]]。但是,我的问题是当我尝试更改不在第 0 列中的元素时,因此问题显然在于“减少列”步骤。
change_elem 2 1 7 [[1,2,3],[4,5,6],[1,2,0]] 给出输出
[[1,2,3],[4,5,6],[1],[7,0]]。它的行为是将给定行的较早元素分成单例列表。
change_elem 0 4 10 [[0,1,2,3,4,5,6]] 产生[[0],[1],[2],[3],[10,5,6]]
(++) 运算符不应该将较早的元素返回到列表中,留下一个统一的行吗?
我曾尝试在结果列表上调用 concat,但是当我将行修改为:
... concat $ [[y]] ++ change_elem 0 (col-1) x (ys:ls)
我收到一个很长的错误,但这似乎应该有效。 错误:
Couldn't match expected type ‘[a]’ with actual type ‘a’
‘a’ is a rigid type variable bound by
the type signature for
change_elem :: Int -> Int -> a -> [[a]] -> [[a]]
at test.hs:15:16
Relevant bindings include
ls :: [[a]] (bound at test.hs:23:29)
ys :: [a] (bound at test.hs:23:25)
y :: a (bound at test.hs:23:23)
x :: a (bound at test.hs:23:19)
change_elem :: Int -> Int -> a -> [[a]] -> [[a]]
(bound at test.hs:17:1)
In the expression: y
In the expression: [y]
【问题讨论】:
标签: list haskell concatenation