“问”在Haskell中是什么意思,它与问函数有什么区别? [关闭]

问题描述 投票:-3回答:1

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

我正在阅读Stephen的“学习Haskell时我希望知道的东西,我找到了这个例子:


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```

So, my question is: from where the list was taken?
haskell monads monad-transformers reader-monad
1个回答
2
投票

askasks id。在...时>

do
    x <- asks f
    -- etc.

... x将是在[...]中将f应用于您的MonadReader计算环境的结果>

do
    x <- ask
    -- etc.

... x将是环境本身。

© www.soinside.com 2019 - 2024. All rights reserved.