I plan on doing one post per module, and this first post defines the Maybe monad transformer, which isn't in GHC (yet?) but made our code look much neater.
Check it out!
=======================
Maybe.lhs
> {-# OPTIONS -fallow-undecidable-instances -fglasgow-exts #-}
> module Maybe where
Almost all of this is taken from the Haskell Wiki
> import Control.Monad
> import Control.Monad.Trans
> import Control.Monad.State
> newtype MaybeT m a = MaybeT {runMaybeT :: m (Maybe a)}
> instance Functor m => Functor (MaybeT m) where
> fmap f x = MaybeT $ fmap (fmap f) $ runMaybeT x
> instance Monad m => Monad (MaybeT m) where
> return = MaybeT . return . return
> x >>= f = MaybeT $ runMaybeT x >>= maybe (return Nothing) (runMaybeT . f)
> fail _ = MaybeT $ return Nothing
> instance Monad m => MonadPlus (MaybeT m) where
> mzero = MaybeT $ return mzero
> mplus x y = MaybeT $ liftM2 mplus (runMaybeT x) (runMaybeT y)
> instance MonadTrans MaybeT where
> lift = MaybeT . liftM return
Here are my contributions, which I shoudl proabbly give back to the wiki: the MonadIO instance and the MonadState instance. You'd think these would generalize to any instance of MonadTrans, seeing as I only use lift. I haven't tried it yet.
> instance MonadIO m => MonadIO (MaybeT m) where
> liftIO = lift . liftIO
My Haskell-fu isn't good enough to make the instance of MonadState work without -fallow-undecidable-instances. If anyone knows why, let me know.
> instance (MonadState s m) => MonadState s (MaybeT m) where
> get = lift get
> put = lift . put
2 comments:
good post :)
Have you heared about 9Dragons which you need use 9Dragons gold to play, and you can also borrow 9 Dragons gold from other players? But you can buy 9 Dragons gold, or you will lose the choice if you do not have cheap 9Dragons gold. If you get 9Dragons money, you can
Post a Comment