Haskell-将元素插入2D数组中的第n个位置

时间:2018-12-18 17:30:55

标签: arrays haskell 2d

如何将元素插入2D数组? 这是一个示例:

insert2D 732 2 1 [[1..3],[4..6],[7..9]] = [[1, 2, 3], 
                [4, 5, 732],[7, 8, 9]]

我设法用列表做到了:

insert :: a -> Int -> [a] -> [a]
insert x n xs = take n xs ++ [x] ++ drop (n + 1) xs

2 个答案:

答案 0 :(得分:0)

如果您显式编写递归,而不是使用takedrop,则更容易看到该模式。

-- Either replace the old first element with the new first element,
-- or insert the new element into the tail of the list and prepend
-- the old first element.
insert1D :: a -> Int -> [a] -> [a]
insert1D x' 0 (_:xs) = x':xs
insert1D x' p (x:xs) = x : insert1D x' (p - 1) xs

-- Likewise, either replace the old first row with a new first row
-- (which you get using insert1D), or insert the new element into
-- the tail of the array and prepend the old first row.
insert2D :: a -> Int -> Int -> [[a]] -> [[a]]
insert2D x'  0 py (r:rs) = insert1D x' py r : rs
insert2D x' px py (r:rs) = r : insert2D x' (px - 1) py rs

比较基本情况和基本情况:

insert1D x' 0    (_:xs) = x'               : xs
insert2D x' 0 py (r:rs) = insert1D x' py r : rs

以及归纳案例到归纳案例:

insert1D x' p     (x:xs) = x : insert1D x' (p - 1)     xs
insert2D x' px py (r:rs) = r : insert2D x' (px - 1) py rs

(如果您想象像这样的函数,两者甚至会更加相似

-- A zero-dimensional array is just a single element. To
-- "insert" a new element, we just ignore the old one and
-- return the new one.
insert0D :: a -> a -> a
insert0D = flip const

insert1D的定义中使用,而不是直接使用x'

insert1D x' 0    (_:xs) = insert0D x'    x : xs
insert2D x' 0 py (r:rs) = insert1D x' py r : rs

答案 1 :(得分:0)

如果您使用数组,而不是问题所显示的列表,则:

India Delhi, UK London, US Newyork 
Los Angeles
Europe France 
Paris