[Haskell-beginners] Mixing monads?

Ron Leisti ron.leisti at gmail.com
Sun Mar 28 11:41:24 EDT 2010


I've run into a situation where I need to 'weave' two monads together,
but I can't figure out how it's done.

The first monad is "Parser a" from Attoparsec, and the second is one
that I've created called "CBC a", with the following relevant
functions:

-- Decrypts a word in cipher-block-chaining mode
decryptCBC :: Word128 -> CBC Word128

-- Performs a cipher-block-chaining mode operation with the given
-- key and initialization vector.
cbc :: Key -> IV -> CBC a -> a

I've also defined a special parser for Attoparsec, for extracting the
next 128 bit word from the stream:
word128 :: Parser Word128

My problem is that I would like to write a function which reads a
word, decrypts it, and then uses the result to make a decision about
whether to read further words or return a result.

So far, I think my function would have a result type of:

func :: Parser (CBC foo)

but within the function, if I do something like:
func = do
    x <- word128
    let r = do
        y <- decryptCBC x
        if (predicate y)
            then return bar
            else -- somehow read more from the parser?
    return r

But within this function I run into the situation where my types turn
into something like Parser (CBC (Parser a)).

I have a feeling that I'm just going about this in a wrong way.  I
realize that I probably don't need to use Parser here, since I'm just
reading a stream of words, but I'd still like to learn how to do this
in the general case.  Is there anyone that could point me in a better
direction?

Thanks,
Ron


More information about the Beginners mailing list