Newtype behavior in Haskell

I found that I can do this 1 :: Product Int and get Product {getProduct = 1} as a result.

Product is newtype defined in Data.Monoid . Then I tried to define my own newtype as follows:

 newtype Stuff a = Stuff {getStuff :: a} deriving (Show) 

But if I try to make 1 :: Stuff Int , I get an error:

 <interactive>:20:1: error: * No instance for (Num (Stuff Int)) arising from the literal `1' * In the expression: 1 :: Stuff Int In an equation for `it': it = 1 :: Stuff Int 

Should I put a Num restriction on a or something else? Why is this not working?

+6
source share
1 answer

You can do 1 :: T if and only if T is an instance of Num . 1 :: Product Int works because Product defines an instance of instance Num a => Num (Product a) (i.e. if a is an instance of Num , Product a also an instance of Num ).

Should I set a Num limit on something?

You must define a Num instance for Stuff Int (or better for Num a => Stuff a ).

You can do this manually (using instance ) or automatically using the deriving Num extension and GeneralizedNewtypeDeriving , which will define a Num instance for Num a => Stuff a , which acts exactly like a Num instance for given a .

+15
source

All Articles