"ask"在Haskell中是什么意思,它和"asks"函数有什么区别?
What does "ask" mean in Haskell and what's the difference of it and "asks" function?
我不懂ask
函数怎么用,我知道asks
函数怎么用,但不知道有没有关系
我正在阅读 Stephen 的 "What I wish I knew when learning 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
那么,我的问题是:该列表是从哪里获取的?
ask
是 asks id
。在...
do
x <- asks f
-- etc.
...x
将是将 f
应用于您的 MonadReader
计算环境的结果,在...
do
x <- ask
-- etc.
...x
将是环境本身。
我不懂ask
函数怎么用,我知道asks
函数怎么用,但不知道有没有关系
我正在阅读 Stephen 的 "What I wish I knew when learning 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
那么,我的问题是:该列表是从哪里获取的?
ask
是 asks id
。在...
do
x <- asks f
-- etc.
...x
将是将 f
应用于您的 MonadReader
计算环境的结果,在...
do
x <- ask
-- etc.
...x
将是环境本身。