从矩阵替换元素(Haskell)

时间:2013-10-30 23:43:28

标签: haskell matrix

我是Haskell的新手,我必须实现一个简单的tic tac toe游戏。它不需要AI。

我需要更新我的矩阵,但我不知道该怎么做。

这是我糟糕的代码:

import Array

table :: Array (Int, Int) Char
table = array ((1,1),(3,3))
            [
            ((1,1), '0'), ((1,2), '0'), ((1,3), '0'),
            ((2,1), '0'), ((2,2), '0'), ((2,3), '0'),
            ((3,1), '0'), ((3,2), '0'), ((3,3), '0')
            ]

getGrid :: IO()
getGrid = do
    print (elems table)
    putStr "Escolha o numero da casa em que deseja jogar: "
    n <- getChar
    if isValid n == (0, 0) then
        getGrid
    else if (table ! isValid n) == '0'  then do
            putStr "\nProssiga: "
            getPlayer n
        else do
            putStr "\nCasa ocupada, tente novamente: "
            getGrid

getPlayer :: Char -> IO()
getPlayer n = do
    putStr "\nJogador X: "
    j <- getChar
    if (j /= 'b' && j /= 'B' && j /= 'p' && j /= 'P') then do
        getPlayer n
    else    do
        (table ! isValid n) = j
        getGrid


isValid :: Char -> (Int,Int)
isValid n
    | n == '0' = (1, 1)
    | n == '1' = (1, 2)
    | n == '2' = (1, 3)
    | n == '3' = (2, 1)
    | n == '4' = (2, 2)
    | n == '5' = (2, 3) 
    | n == '6' = (3, 1)
    | n == '7' = (3, 2)
    | n == '8' = (3, 3)
    | otherwise = (0, 0)

我不知道如何用其他值替换0 ...:/

2 个答案:

答案 0 :(得分:2)

您可以使用阵列上的(//)函数来设置新值。

答案 1 :(得分:2)

您无法更新数组就地,因为默认的Array类型是不可变的。

然而,无论如何,做你想做的事情都很容易。只需使用//运算符(documentation)生成新数组:

您可以这样做:

setValue :: (Int, Int) -> Int -> Array -> Array
setValue (x,y) a ar = ar // [((x,y), a)]

例如,在我的国际象棋代码中,我有:

applyMove :: PieceMove -> Board -> Board
applyMove ((x,y), (a,b)) board = board // [((x,y), (Square Nothing)),
                                           ((x+a,y+b), board!(x,y))]