且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

`变量不在范围内`在一个简单的函数中

更新时间:2022-10-29 13:23:02

由于我没有整个haskell文件,我只能给出一个有教养的猜测 - 但你是如果.. then .. else 表达式

这应该是正确的假设 put 返回一个新的 Board - 并且与 State 无关>:

  pvp :: Board  - > Int  - > IO()
pvp board player = do
player1choice< - prompt $(Player++(show(player + 1))++,轮到你了:)
让newboard = if玩家== 0
然后把棋盘X(读取player1choice)
放到棋盘上O(读取player1choice)
case newboard
Nothing - >做
putStrLn无效移动。
- playGame b
只需登上' - > putStrLn有效移动。



注意(与您的问题无关)



你应该避免 read 如果有人输入了一个无效的输入,它会使你的程序崩溃 - 比如说你期望一些数字的字母。更好地使用 readMaybe


Consider the next piece of code -

pvp::Board->Int-> IO ()
pvp board player = do
  player1choice <- prompt $ ("Player " ++  (show (player + 1)) ++ ", it's your turn:")

  if player == 0 
    then let newboard = (put board X (read player1choice)) in newboard
    else let newboard = (put board O (read player1choice)) in newboard

  case newboard of
    Nothing -> putStrLn "Invalid move."
    Just board' -> putStrLn "Valid move."

For case newboard of, i get error: Variable not in scope: newboard :: Maybe a0. whats the reason for this?

Since I have not the whole haskell file I can only give an educated guess - but you are having newboard only in scope of your if .. then .. else expression

This should be correct assuming put is returning a new Board - and has nothing to do with State:

pvp :: Board -> Int -> IO ()
pvp board player = do
  player1choice <- prompt $ ("Player " ++  (show (player + 1)) ++ ", it's your turn:")
  let newboard = if player == 0
                   then put board X (read player1choice)
                   else put board O (read player1choice)
  case newboard of
      Nothing -> do
        putStrLn "Invalid move."
        -- playGame b
      Just board' -> putStrLn "Valid move."

Note (unrelated to your problem)

You should avoid read it will crash your program if someone enters an invalid input - say a letter where you expect something numeric. better use readMaybe