【发布时间】:2012-11-11 07:31:28
【问题描述】:
这是我的代码:
getMove :: Board -> Player -> IO (Maybe (Move, Board, Player))
completeUserTurn :: Player -> Board -> Maybe (IO (Board, Player))
completeUserTurn player board = do
m <- getMove board player --error is here
if isNothing m then
Nothing
else do
let (move, updatedBoard, updatedPlayer) = fromJust m
if isMoveValid board move then do
continue <- prompt $ displayToUserForPlayer updatedBoard updatedPlayer ++ "\n" ++ "Is this correct? (y/n): "
if continue == "y" then
return (updatedBoard, updatedPlayer)
else
completeUserTurn player board
else do
putStr "Invalid Move!\n"
completeUserTurn player board
这是我得到的错误(在指示的行上):
Couldn't match expected type `Maybe t0'
with actual type `IO (Maybe (Move, Board, Player))'
In the return type of a call of `getMove'
In a stmt of a 'do' block: m <- getMove board player
In the expression:
do { m <- getMove board player;
if isNothing m then
Nothing
else
do { let ...;
.... } }
怎么了?我虽然 <- 会执行 IO 操作并将结果放在 m 中?那为什么它会期待Maybe呢?
【问题讨论】:
-
因为一旦你进入了 IO monad,就无法逃脱!您是否尝试过将类型签名更改为它建议的类型?
-
你给出的类型是一个纯函数的类型,它可能会给你一个 IO 来执行,而一旦你在 do 块中使用 getMove,你就会把它变成 IO 类型(东西) .您也需要更改 Nothing 以返回 Nothing。
-
您还需要将
return (updatedBoard, updatedPlayer)更改为return (Just (updatedBoard, updatedPlayer))以匹配。 -
completeUserTurn的类型签名没有意义。如果有的话,它应该返回IO ( Maybe(...) )。