Search code examples
haskellnewtype

When do we use newtype in Haskell?


I'm a bit confused with type and newtype. It is said that newtype can contain only one field. I also find a post here.

But still not quite clear.

So if you want to declare different type class instances for a particular type, or want to make a type abstract, you can wrap it in a newtype and it'll be considered distinct to the type-checker, but identical at runtime.

Any example would be helpful. Thank you!


Solution

  • An example usage collected from the quote you posted would perhaps be declaring two Int monoids. There are multiple ways to consider Int a monoid (multiplication or addition), and perhaps you wish to use more than one. You can not define more than one monoid instance for Int, but you can instead create two newtypes and provide separate instances for them.

    newtype SumInt = SumInt Int 
    newtype ProdInt = ProdInt Int 
    
    instance Monoid SumInt where
      mempty = SumInt 0
      (SumInt a) `mappend` (SumInt b) = SumInt (a + b)
    
    instance Monoid ProdInt where
      mempty = ProdInt 1
      (ProdInt a) `mappend` (ProdInt b) = ProdInt (a*b)