【发布时间】:2021-08-06 08:32:17
【问题描述】:
我正在尝试理解 Reader monad,我正在关注这个答案 https://stackoverflow.com/a/14179721/10116440,其中包含以下示例:
import Control.Monad.Reader
data GameState = NotOver | FirstPlayerWin | SecondPlayerWin | Tie
data Game position
= Game {
getNext :: position -> [position],
getState :: position -> GameState
}
getNext' :: position -> Reader (Game position) [position]
getNext' position
= do game <- ask
return $ getNext game position
getState' :: position -> Reader (Game position) GameState
getState' position
= do game <- ask
return $ getState game position
negamax :: Double -> position -> Reader (Game position) Double
negamax color position
= do state <- getState' position
case state of
FirstPlayerWin -> return color
SecondPlayerWin -> return $ negate color
Tie -> return 0
NotOver -> do possible <- getNext' position
values <- mapM ((liftM negate) . negamax (negate color)) possible
return $ maximum values
首先我不明白的是return $ getNext game position。 getNext,当应用于 game 时,返回 position -> [position]。这在应用于position 时返回[position]。所以return $ getNext game position 行应该返回Reader (Game position) [position] 以外的其他东西,我不知道这是什么东西,因为我不知道return 是如何为Reader monad 定义的。
无论如何,Game 中的哪个“实例”将 ask 返回?我不明白,这段代码中没有。另外,runReader 永远不会被调用,那么getNext、getState 和negamax 的Reader 结果是用来做什么的?
谁能完成这个示例,说明runReader 将如何在这段代码中实际运行,以及ask 返回哪个game 实例?
另外,为什么是Reader env a 而不仅仅是Reader a?
【问题讨论】:
-
你问,“为什么是
Reader env a而不仅仅是Reader a?”。让我转过头来:假设我们以Reader a的想法运行;你对data Reader a = {- ... -}的RHS有什么建议?