[Haskell-cafe] Monad transformer to consume a list

Stephan Friedrichs deduktionstheorem at web.de
Tue Apr 7 15:35:41 EDT 2009


My solution is this transformer:



newtype ConsumerT c m a
    = ConsumerT { runConsumerT :: [c] -> m (a, [c]) }

instance (Monad m) => Monad (ConsumerT c m) where
    return x = ConsumerT $ \cs -> return (x, cs)
    m >>= f  = ConsumerT $ \cs -> do
                 ~(x, cs') <- runConsumerT m cs
                 runConsumerT (f x) cs'
    fail msg = ConsumerT $ const (fail msg)

consume :: (Monad m) => ConsumerT c m (Maybe c)
consume = ConsumerT $ \css -> case css of
                               []     -> return (Nothing, [])
                               (c:cs) -> return (Just c, cs)

consumeAll :: (Monad m) => ConsumerT c m [c]
consumeAll = ConsumerT $ \cs -> return (cs, [])


-- 

Früher hieß es ja: Ich denke, also bin ich.
Heute weiß man: Es geht auch so.

 - Dieter Nuhr


More information about the Haskell-Cafe mailing list