----------------------------------------- --- Example of another Monad: Maybe ----------------------------------------- type CarReg = String type PersonNummer = String type Name = String carRegister :: [(CarReg,PersonNummer)] carRegister = [("FYN 433","850219-1234"), ("GYN 434","850219-1234"), ("JBD 007","750408-0909")] nameRegister :: [(PersonNummer,Name)] nameRegister = [("750408-0909","Dave"), ("850219-1234","Bob"), ("890929-C234","Pierre")] data Offence = Speeding | DrunkDriving | CarTheft deriving Show crimeRegister :: [(Name,Offence)] crimeRegister = [("Dave",Speeding)] suspiciousCar :: CarReg -> Maybe (Name, PersonNummer, Offence) -- given a registration number, -- returns the name, personal number and offence of the owner, -- if all of these are defined. suspiciousCar car = case lookup car carRegister of Nothing -> Nothing Just p -> case lookup p nameRegister of Nothing -> Nothing Just n -> case lookup n crimeRegister of Nothing -> Nothing Just c -> Just (n,p,c) -- Monadic style: test = do return 32 x <- Nothing return 42 -- Just 32 >> Nothing >>= \x -> Just 42 suspiciousCar' car = do pnr <- lookup car carRegister name <- lookup pnr nameRegister crime <- lookup name crimeRegister return (name,pnr,crime) -- equivalent to the above, with part of the do -- unrolled: suspiciousCar'' car = lookup car carRegister >>= (\p -> lookup p nameRegister >>= (\n -> do c <- lookup n crimeRegister return (n,p,c) ) ) -- (parens added only to emphasise scope) {- from the Prelude: instance Monad Maybe where return = Just Nothing >>= f = Nothing (Just x) >>= f = f x -}