-3

我不明白如何使用该ask功能,我知道如何使用该asks功能,但我不知道它们是否相关。

我正在阅读斯蒂芬的“我希望在学习 Haskell 时知道什么”,我发现了这个例子:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.State

type Stack = [Int]
type Output = [Int]
type Program = [Instr]

type VM a = ReaderT Program (WriterT Output (State Stack)) a

newtype Comp a = Comp { unComp :: VM a }
    deriving (Functor, Applicative, Monad, 
                MonadReader Program, MonadWriter Output, 
                  MonadState Stack)

data Instr = Push Int
            | Pop
            | Puts

evalInstr :: Instr -> Comp ()
evalInstr instr = case instr of
                    Pop -> modify tail
                    Push n -> modify (n:)
                    Puts -> do
                        tos <- gets head
                        tell [tos]

eval :: Comp ()
eval = do
    instr <- ask
    case instr of
      [] -> return ()
      (i:is) -> evalInstr i >> local (const is) eval

execVM :: Program -> Output
execVM = flip evalState [] . execWriterT . runReaderT (unComp eval)

program :: Program
program = [
        Push 42,
        Push 27,
        Puts,
        Pop,
        Puts,
        Pop
    ]

main :: IO ()
main = mapM_ print $ execVM program

所以,我的问题是:从哪里获取列表?

4

1 回答 1

3

askasks id。而在...

do
    x <- asks f
    -- etc.

...x将是应用于f您的MonadReader计算环境的结果,在...

do
    x <- ask
    -- etc.

...x将是环境本身。

于 2020-05-28T18:55:36.443 回答