【发布时间】:2017-11-13 14:58:30
【问题描述】:
我有一些像这样的变量:
let y0 = read (input!!0) :: Int
let h = read (input!!1) :: Int
y <- newIORef y0
minY <- newIORef 0
maxY <- newIORef (h - 1)
后来我有了
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
我基本上是将引用读入一些本地整数,然后尝试根据标准更新引用。
我也试过modifyIORef maxY (y_old - 1),但这也不起作用。编译器只告诉我“解析错误”或“语法错误”,这没有帮助。
我的完整代码:
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
【问题讨论】:
-
如果你只有两个子句,你只需要
if something then something else something而不是另一个if。如果您已经阅读过 ioref,那么您可能想要使用 writeIORef。此外,您确定需要 IORef 吗?很多时候它可以做得更好。 -
请给minimal reproducible example。如果你有解析错误,你可能没有正确使用
do语法。 -
这看起来像你想用 Haskell(函数式语言)编写命令式程序。虽然这当然是可能的,但通常这样做是一个非常糟糕的主意。您也没有为最后一个
if案例提供else。使用(!!)通常也是一种反模式,因为它是一个非全部(并且对于任意索引效率低下)函数。 -
@leftaroundabout 我不能在这里提供完整的 MCVE,因为它是在线游戏的一部分
-
@WillemVanOnsem 你说得对,我正在尝试编写命令式风格——这是因为我不知道如何使用非命令式风格编写我想要的程序。确实浪费了 4 天的时间试图做到这一点而没有任何进展——所以在我完成问题/看看其他人是怎么做的/从中吸取教训之前,我会用 IORefs 来嘲笑它。
标签: variables haskell syntax reference