替换嵌套列表中的元素

时间:2019-11-07 04:01:10

标签: haskell

我正在解决数独问题,并尝试创建一个setBoardAt函数,该函数将使用setRowAt函数将板中某一行中的值之一更新为新值。

setRowAt :: Sequence -> Int -> Int -> Sequence
setRowAt s i v = take i s ++ [v] ++ drop (i + 1) s

setBoardAt :: Board -> Int -> Int -> Int -> Board
setBoardAt b i j v = take i b ++ [setRowAt [s] j v | s <- b !! i] ++ drop (i + 1) b 

在我的主菜单中,我可以使用setRowAt函数并使用在setBoardAt函数中映射的内容返回预期结果

main = do

  args <- getArgs
  txt  <- readFile (head args)
  let board1 = getBoard txt
  print board1
  let seq1 = board1 !! 5
  print seq1
  let row1 = setRowAt seq1 2 5
  print row1
  let nboard1 = take 1 board1 ++ [row1] ++ drop (1 + 1) board1

收到的结果正确

[[5,3,0,0,7,0,0,0,0],[6,0,0,1,9,5,0,0,0],[0,9,8,0,0,0,0,6,0],[8,0,0,0,6,0,0,0,3],[4,0,0,8,0,3,0,0,1],[7,0,0,0,2,0,0,0,6],[0,6,0,0,0,0,2,8,0],[0,0,0,4,1,9,0,0,5],[0,0,0,0,8,0,0,7,9]]
[7,0,0,0,2,0,0,0,6]
[7,0,5,0,2,0,0,0,6]

但是当我尝试使用具有相同参数的setBoardAt函数和嵌套的setRowAt函数时,我要处理的行返回错误,并且我无法查明原因。

main = do

  args <- getArgs
  txt  <- readFile (head args)
  let board1 = getBoard txt
  print board1
  let test1 = setBoardAt board1 5 2 5
  print test1

[[5,3,0,0,7,0,0,0,0],[7,0,5,0,2,0,0,0,6],[0,9,8,0,0,0,0,6,0],[8,0,0,0,6,0,0,0,3],[4,0,0,8,0,3,0,0,1],[7,0,0,0,2,0,0,0,6],[0,6,0,0,0,0,2,8,0],[0,0,0,4,1,9,0,0,5],[0,0,0,0,8,0,0,7,9]]
[[5,3,0,0,7,0,0,0,0],[6,0,0,1,9,5,0,0,0],[0,9,8,0,0,0,0,6,0],[8,0,0,0,6,0,0,0,3],[4,0,0,8,0,3,0,0,1],[7,5],[0,5],[0,5],[0,5],[2,5],[0,5],[0,5],[0,5],[6,5],[0,6,0,0,0,0,2,8,0],[0,0,0,4,1,9,0,0,5],[0,0,0,0,8,0,0,7,9]]

任何建议或见解将不胜感激。

1 个答案:

答案 0 :(得分:0)

您在setRowAt中没有正确使用setBoardAt

您现在正在做的是从一行中获取每个元素,并将包含该元素的列表传递给setRowAt函数。相反,您应该执行以下操作

setBoardAt b i j v = take i b ++ [setRowAt (b!!i) j v] ++ drop (i + 1) b