Celso
Celso

Reputation: 13

Replace an element from a matrix (Haskell)

I'm new to Haskell and I have to implement a simple tic tac toe game. It doesn't need AI.

I need to update my matrix but I don't know how to do it.

Here is my crappy code:

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)

I don't know what to do to replace the 0s with other values... :/

Upvotes: 1

Views: 1617

Answers (2)

Christian Ternus
Christian Ternus

Reputation: 8492

You can't update the array in-place, since the default Array type is immutable.

However, it's pretty easy to do what you want anyway. Simply use the // operator (documentation) to generate a new array:

You might do:

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

For example, in my chess code, I have:

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

Upvotes: 3

Frerich Raabe
Frerich Raabe

Reputation: 94279

There's a (//) function on Arrays you can use to set a new value.

Upvotes: 2

Related Questions