Monad Maybe?

Pixel pixel@mandrakesoft.com
22 Sep 2002 00:40:46 +0200


"Russell O'Connor" <roconnor@Math.Berkeley.EDU> writes:

> [To: haskell-cafe@haskell.org]
> 
> Is there a nicer way of writing the following sort of code?
> 
> case (number g) of
>  Just n -> Just (show n)
>  Nothing ->
>   case (fraction g) of
>    Just n -> Just (show n)
>    Nothing ->
>     case (nimber g) of
>      Just n -> Just ("*"++(show n))
>      Nothing -> Nothing

what about?

 listToMaybe $ mapMaybe (\ (f, format) -> fmap format (f g)) l
 where l = [ (number, show), (fraction, show), (nimber, (\ n -> "*" ++ show n)) ]

or:

 if_just (number g) show $
 if_just (fraction g) show $ 
 if_just (nimber g) (\ n -> "*" ++ show n) Nothing

    using:
    
    if_just (Just e) f _ = Just(f e)
    if_just Nothing _ f = f