我正在尝试使用 Haskell 中的函数 setElem 来更新矩阵,但似乎新值不会留在矩阵中。有没有办法使用这个功能来解决这个问题?
我是 Haskell 的新手,我需要在矩阵中设置一个新值,然后显示更新的矩阵。
setElem::a -> (Int, Int) -> 矩阵 a -> 矩阵 a
我的代码:
import Data.Matrix
import System.Random
import System.IO
import Data.Array
table_game = matrix 20 20 $ \(i,j)-> "#"
inputCoordenadas = do
putStrLn "Digite -1 -1 para encerrar: "
putStrLn "Digite a coordenada X: "
coord_x <- getLine
putStrLn "Digite a coordenada Y: "
coord_y <- getLine
let x = (read coord_x :: Int)
let y = (read coord_y :: Int)
if(coord_x == "-1" && coord_y=="-1") then do
putStrLn ("Encerrando o jogo...")
return ()
else do
print $ setElem "X" (2,2) table_game
print table_game
inputCoordenadas
main = do
putStrLn "Iniciar jogo|1 - Encerrar jogo|0: "
buffer <- getLine
let n = (read buffer :: Int)
if n==0 then do
putStrLn "Encerrando o jogo"
return ()
else do
print table_game
inputCoordenadas
最佳答案
Haskell 使用纯函数。纯函数不能脱离上下文修改任何内容并防止副作用。您正在尝试的是 Haskell 中的一种罪过。设置一个全局变量并试图改变它是不行的。
您基本上应该构造您的代码,以便 inputCoordenadas
函数接受一个桌面游戏(tg
在我下面的代码中),打印它,修改它并返回一个新的桌面游戏。只需最少的更改,您的代码应该就像
import Data.Matrix
import System.Random
import System.IO
import Data.Array
inputCoordenadas tg = do
print tg
putStrLn "Digite -1 -1 para encerrar: "
putStrLn "Digite a coordenada X: "
coord_x <- getLine
putStrLn "Digite a coordenada Y: "
coord_y <- getLine
let x = (read coord_x :: Int)
let y = (read coord_y :: Int)
if(coord_x == "-1" && coord_y=="-1") then putStrLn "Encerrando o jogo..."
else inputCoordenadas $ setElem "X" (x,y) tg
main = do
putStrLn "Iniciar jogo|1 - Encerrar jogo|0: "
buffer <- getLine
let n = (read buffer :: Int)
if n==0 then putStrLn "Encerrando o jogo"
else inputCoordenadas $ matrix n n (\(i,j) -> "#")
关于haskell - 如何在 Haskell 中使用 setElem 更新矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58886388/