[Haskell-beginners] Newtype to avoid orphans

Brent Yorgey byorgey at seas.upenn.edu
Mon Feb 6 14:53:14 CET 2012


On Mon, Feb 06, 2012 at 10:31:50AM +0100, Adrien Haxaire wrote:
> Hello,
> 
> In the library I am writing, I declare a type Vector for Data.Vector
> Double. I then create a Num instance for it as it doesn't have one
> yet. GHC tells me that this instance is an orphan. After reading
> several answers to issues like mine, I want to get rid of these
> orphans. The advice I saw mostly is to use the newtype keyword.
> 
> Is there a way to do it nicely, instead of copying most of the API of
> Data.Vector ?
> 
> Now, the only thing I can see is do like in this example:
> 
> import Data.Vector as V
> 
> newtype VectorD = VectorD (V.Vector Double)
> 
> map :: (Double -> Double) -> VectorD -> VectorD
> map f (VectorD v) = VectorD $ V.map f v
> 
> 
> Is there a better way ?

Yes: don't bother.  Having an orphan instance is really not that big
of a deal.  And it's certainly not worth making a newtype just to
avoid the warning.  If you want to turn off the warning you can add

{-# OPTIONS_GHC -fno-warn-orphans #-}

to the top of your file.

-Brent



More information about the Beginners mailing list