haskell - 如何在 Haskell 中使用 setElem 更新矩阵

标签 haskell matrix

我正在尝试使用 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/

相关文章:

python - 使用 numpy 将向量转换为掩码矩阵

r - 从 lmer 对象 (lme4, R) 中提取随机效应的原始模型矩阵

c++ - 如何像 C++ 中的函数一样存储参数矩阵

Haskell inline-c-cpp调用Haskell函数

haskell - 初始编码如何转换为正确的关联结构?

C++测试矩阵是否已经初始化

c++ - 如何处理非常大的矩阵(例如 1000000 x 1000000)

haskell - 重构使用 Reader monad 的 Haskell 函数

haskell - 使用 IxSet,我可以围绕任意可索引类型构建可索引包装吗?

haskell - 如何最好地提供字节串上的通用接口(interface)?