[Haskell-cafe] what exactly does "deriving (Functor, Monad, MonadIO)" do?

David House dmhouse at gmail.com
Tue May 1 09:44:17 EDT 2007


On 01/05/07, Brandon S. Allbery KF8NH <allbery at ece.cmu.edu> wrote:
> I think all this does is save you from having to write a bunch of
> wrappers that unwrap the contained value, do something to it, and
> rewrap the result.

Exactly. Basically what newtype deriving does is if you have a
declaration like the following:

  newtype T = TConstructor M

And M instantiates some class (like Monad, Functor etc), you can
derive that class for T. For example, here's how the Functor instance
would look for the following newtype:

  newtype MyMaybe a = MM (Maybe a) deriving (Functor)

  -- The instance looks like this:
  instance Functor MyMaybe where
    fmap f (MM a) = MM (fmap f a)

The instance just unwraps and rewraps the newtype constructor.

-- 
-David House, dmhouse at gmail.com


More information about the Haskell-Cafe mailing list