10

我使用 Operational Monad 方法编写了一个具有 Writer 功能的 monad。然后我注意到它不能懒惰地工作。

在下面的代码中,有一个rogueWriter执行无限多个语句的语句,每个语句都写入一个字符串。程序不会终止,只需要无限输出的一些字符。

经过我的分析,我注意到流氓作家实际上非常友好(哈哈),因为当我从runMyWriter rogueWriter变为时runWriter rogueWriter,一切都很顺利。

问题:

  1. 如何最好地解释这种行为?
  2. 我应该如何更改我的代码以使其正常工作?
  3. 什么单子变压器分别SomeMonadT出现了同样的问题
    SomeMonadT Writer wWriterT w SomeMonad (也许有一些例子?)

编辑:我是否有可能在这里尝试反转无限字符串?Sjoerd Visscher 的解决方案与我的解决方案之间的显着区别是

w `mappend` ws  resp.  ws `mappend` w

代码:

{-# LANGUAGE GADTs, FlexibleContexts, TypeSynonymInstances,
                    FlexibleInstances, MultiParamTypeClasses #-}

module Writer where

import Control.Monad.Identity
import Control.Monad.Operational
import Control.Monad.Writer
import Data.Monoid

data MyWriterI w a where
    Tell :: w -> MyWriterI w ()

type MyWriterT w = ProgramT (MyWriterI w)

type MyWriter w = (MyWriterT w) Identity

runMyWriterT :: (Monad m, Monoid w) => MyWriterT w m a -> m (a, w)
runMyWriterT prog = run prog mempty
  where
    run prog ws = viewT prog >>= flip eval ws
    eval (Return a)       ws = return (a, ws)
    eval (Tell w :>>= is) ws = run (is ()) (ws `mappend` w)

runMyWriter :: (Monoid w) => MyWriter w a -> (a, w)
runMyWriter prog = runIdentity (runMyWriterT prog)

instance (Monad m, Monoid w) => MonadWriter w (MyWriterT w m) where
    tell   = singleton . Tell
    listen = undefined
    pass   = undefined

-- Demonstration of the problem:

rogueWriter :: MonadWriter String m => m ()
rogueWriter = mapM_ (tell . show) [1..]

main = let (_, infiniteOutput) = runMyWriter rogueWriter
       in putStrLn (take 20 infiniteOutput)
4

1 回答 1

6

我不知道你的程序为什么会失败,但我会这样写:

runMyWriterT prog = run prog
  where
    run prog = viewT prog >>= eval
    eval (Return a)       = return (a, mempty)
    eval (Tell w :>>= is) = do
      ~(r, ws) <- run (is ())
      return (r, w `mappend` ws)
于 2011-12-26T12:29:33.310 回答