问题描述
考虑下一段代码 -
pvp :: Board-> Int-> IO()
pvp board player = do
player1choice< - prompt $(Player++(show(player + 1))++,轮到你了:)
if player == 0
然后让newboard =(把棋盘X(读取player1choice))放到新棋盘
中else newboard =(把棋盘O(读取player1choice))放到新棋盘
案例
的新案例Nothing - > putStrLn无效移动。
只需登上' - > putStrLn有效移动。
对于 case newboard of
,我得到 error:变量不在范围内:newboard :: Maybe a0
。这是什么原因?
由于我没有整个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
如果有人输入了一个无效的输入,它会使你的程序崩溃 - 比如说你期望一些数字的字母。更好地使用
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
这篇关于`变量不在范围内`在一个简单的函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!