Home How do I update the values of these Int refs (Haskell)?
Reply: 0

How do I update the values of these Int refs (Haskell)?

user2657
1#
user2657 Published in May 24, 2018, 4:01 pm

I have some variables like so:

let y0 = read (input!!0) :: Int
let h = read (input!!1) :: Int
y <- newIORef y0
minY <- newIORef 0 
maxY <- newIORef (h - 1) 

And later I have

y_old <- readIORef y

if (some_string!!0 == 'U') then   
    maxY = (y_old - 1)       --I don't think this is working
else if (some_string!!0 == 'D') then
    minY = (y_old + 1)       --I don't think this is working

I am basically reading the references into some local ints and then trying to update the references based on criteria.

I also tried modifyIORef maxY (y_old - 1) but this doesn't work either. The compiler is only telling me "parse error" or "syntax error" which is not helpful.

My full code:

import System.IO
import Control.Monad
import Data.IORef
import Text.Printf

main :: IO ()
main = do
    hSetBuffering stdout NoBuffering -- DO NOT REMOVE

    -- Auto-generated code below aims at helping you parse
    -- the standard input according to the problem statement.

    input_line <- getLine
    let input = words input_line
    let w = read (input!!0) :: Int -- width of the building.
    let h = read (input!!1) :: Int -- height of the building.
    input_line <- getLine
    let n = read input_line :: Int -- maximum number of turns before game over.
    input_line <- getLine
    let input = words input_line
    let x0 = read (input!!0) :: Int
    let y0 = read (input!!1) :: Int
    x <- newIORef x0
    y <- newIORef y0
    minX <- newIORef 0 
    maxX <- newIORef (w - 1) 
    minY <- newIORef 0 
    maxY <- newIORef (h - 1) 
    loop x0 y0 w h x y minX maxX minY maxY

loop :: Int -> Int -> Int -> Int -> IORef Int -> IORef Int -> IORef Int -> IORef Int-> IORef Int -> IORef Int -> IO ()
loop x0 y0 w h x y minX maxX minY maxY = do
    input_line <- getLine
    let bombdir = input_line :: String -- the direction of the bombs from batman's current location (U, UR, R, DR, D, DL, L or UL)

    x_old <- readIORef x 
    y_old <- readIORef y

    if (bombdir!!0 == 'U') then
        writeIORef maxY (y_old - 1)
    if (bombdir!!0 == 'D') then
        writeIORef minY (y_old + 1)

    if (bombdir!!(bombdir.length-1) == 'L') then
        writeIORef maxX (x_old - 1)
    if (bombdir!!(bombdir.length-1) == 'R') then
        writeIORef minX (x_old + 1)


    x = (minX + maxX) / 2
    y = (minY + maxY) / 2

    x_out <- readIORef x 
    y_out <- readIORef y


    printf "%d %d" x_out y_out
    loop x0 y0 w h x y minX maxX minY maxY
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.358789 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO