Identity as a transformer: IdentityT

Here’s a somewhat “silly” transformer. I’ve been thinking about it for a few days but didn’t find the time for it until tonight. Never ever having written even a monad on my own I did find the thought of a transformer more than a little daunting. As so often before I don’t really have any novel ideas and DonS had already done the same thing (thanks to chess in #haskell for helping me find it). After seeing his code I cleaned mine up (and copied some things I had “saved for later”). Here’s the resulting monad transformer:

newtype IdentityT m a = IdentityT { runIdentityT :: m a }

instance (Monad m) => Monad (IdentityT m) where
    return = IdentityT . return
    m >>= k = IdentityT $ runIdentityT . k =<< runIdentityT m
    fail msg = IdentityT $ fail msg

instance (MonadIO m) => MonadIO (IdentityT m) where
    liftIO = IdentityT . liftIO

instance (Functor m, Monad m) => Functor (IdentityT m) where
    fmap f = IdentityT . fmap f . runIdentityT

instance MonadTrans IdentityT where
    lift = IdentityT

I’ll get back to what I think it might be useful for in a later post.


It’s no more silly than the number zero :-)


sigfpe, possibly that’s true, but I doubt its contribution to the art can be compared to zero’s. I’m not a Haskell guru, nor am I a mathematician, so I might very well be wrong :-)

Leave a comment