[Haskell-cafe] Composing monads (sort of)

Mark Wassell mwassell at bigpond.net.au
Sat Dec 16 04:34:15 EST 2006


Hi,

I have a set of functions:

f1 :: DBRecord -> Maybe Int
f2 :: Int -> IO Maybe DBRecord
f3 :: DBRecord -> Maybe Int

The odd numbered functions are field accessors, accessing a field that 
might hold an identifier for another record. The even numbered functions 
are record fetch functions that get records from the database. I want to 
compose these so that I can navigate structures of joined records in the 
database.

How can I concisely compose these functions without having to write a 
cascade of case statements such as:

case f1 rec1 of
     Nothing -> return Nothing
     Just id1 -> do
                     rec2 <- f2 id2
                     return $ case rec2 of
                                 Nothing -> return Nothing
                                 Just rec2' -> case f3 rec2' of
                                                 ....
I understand that if I was just dealing with Maybe I could use the fact 
that Maybe is a monad. I am also not sure if composing the IO and the 
Maybe will get me what I want (some of the functions only return Maybe Int).

Cheers

Mark

PS Heard this on the 'West Wing' and thought it was appropriate in a way:

A coach goes up to a player and asks "Are you ignorant or apathetic?". 
The player replies "I don't know and I don't care".


More information about the Haskell-Cafe mailing list