0

我为语句创建了简单的评估器。我想使用变压器来做到这一点 - 将 IO monad 与 State 混合。
有人可以解释怎么做吗?这是我无法处理的东西——变形金刚。

execStmt :: Stmt -> State (Map.Map String Int) ()
execStmt s = case s of
      SAssigment v e -> get >>= (\s -> put (Map.insert v (fromJust (runReader (evalExpM e) s)) s))
      SIf e s1 s2 -> get >>=  (\s -> case (fromJust (runReader (evalExpM e) s)) of
                                        0 -> execStmt s2
                                        _ -> execStmt s1
                              )
      SSkip -> return ()
      SSequence s1 s2 -> get >>= (\s -> (execStmt s1) >>= (\s' -> execStmt s2))
      SWhile e s1 -> get >>= (\s -> case (fromJust (runReader (evalExpM e) s)) of
                                        0 -> return ()
                                        _ -> (execStmt s1) >>= (\s' -> execStmt (SWhile e s1)))

execStmt' :: Stmt -> IO ()
execStmt' stmt =  putStrLn $ show $ snd $ runState (execStmt  stmt) Map.empty
4

1 回答 1

3

这是一个基本的程序大纲

newtype StateIO s a = SIO {runSIO :: s -> IO (a, s)}

put :: s -> StateIO s ()
put s' = SIO $ \_s -> return ((), s')

liftIO :: IO a -> StateIO s a
liftIO ia = SIO $ \s -> do
    a <- ia
    return (a, s)

instance Functor (StateIO s) where
    fmap ab (SIO sa) = SIO $ \s -> do
        (a, s') <- sa s
        let b = ab a
        return (b, s')

instance Applicative (StateIO s) where
    pure a = SIO $ \s -> return (a, s)
    (SIO sab) <*> (SIO sa) = SIO $ \s -> do
        (ab, s' ) <- sab s
        (a , s'') <- sa  s'
        let b = ab a
        return (b, s')

StateIO s a是一种接受输入状态(类型s)的东西,并返回一个 IO 动作来产生一些类型的东西a以及一个新的状态。

要检查是否理解,请执行以下操作

  • 写入一个get :: StateIO s s检索状态的值。
  • Monad (StateIO s)为(与上面的代码类似)编写一个实例。
  • Finally, and this is the big step to understanding transformers, is to define newtype StateT m s a = StateT {run :: s -> m (a, s)}, and translate the above code to that (with the constraint Monad m). This will show you how monad transformers work.
于 2016-04-13T19:24:33.287 回答