Search code examples
haskellnewtype

Using Functions of `a` on `newtype a`


Let's say I have the following newtype:

newtype Foo = Foo Integer deriving (Eq, Show)

Is there a concise way to add two Foo's:

(Foo 10) + (Foo 5) == Foo 15

or get the max:

max (Foo 10) (Foo 5) == Foo 5?

I'm curious if it's possible to easily use functions of a for a newtype a rather than do:

addFoo :: Foo -> Foo -> Foo
addFoo (Foo x) (Foo y) = Foo $ x + y

Solution

  • Just as haskell98 knows how to derive those Eq and Show instances for you, you can turn on the GeneralizedNewtypeDeriving extension to ghc to get the Num and Ord instances you need:

    Prelude> :set -XGeneralizedNewtypeDeriving 
    Prelude> newtype Foo = Foo Integer deriving (Eq, Show, Num, Ord)
    Prelude> (Foo 10) + (Foo 5) == Foo 15
    True
    Prelude> max (Foo 10) (Foo 5) == Foo 5
    False