I'm having some trouble with performing simple addition, subtraction -- any kind of algebra really with Haskells newtype.
My definition is (show included so I can print them to console):
newtype Money = Money Integer deriving Show
What I'm trying to do is basically:
Money 15 + Money 5 = Money 20
Money 15 - Money 5 = Money 10
Money 15 / Money 5 = Money 3
And so on, but I'm getting
m = Money 15
n = Money 5
Main>> m-n
ERROR - Cannot infer instance
*** Instance : Num Money
*** Expression : m - n
I can't find a clear and consise explanation as to how the inheritance here works. Any and all help would be greatly appreciated.
Well Haskell can not add up two
Money
s, since you never specified how to do that. In order to add up twoa
s, thea
s should implement theNum
typeclass. In factnewtype
s are frequently used to specify different type instances, for exampleSum
andProduct
are used to define two different monoids.You thus need to make it an instance of
Num
, so you have to define an instance like:Since
(/) :: Fractional a => a -> a -> a
is a member of theFractional
typeclass, this will give some problems, since yourMoney
wraps anInteger
object.You can however implement the
Integral
typeclass such that it supportsdiv
. In order to do this, we however need to implement theReal
andEnum
typeclass. TheReal
typeclass requires the type to be implement theOrd
, and since theOrd
typeclass requires the object to be an instance of theEq
typeclass, we thus end up implementing theEq
,Ord
,Real
andEnum
typeclass.GeneralizedNewtypeDeriving
As @Alec says we can use a GHC extension named
-XGeneralizedNewtypeDeriving
.The above derivations are quite "boring" here we each time "unwrap" the data constructor(s), perform some actions, and "rewrap" them (well in some cases either unwrapping or rewrapping are not necessary). Especially since a
newtype
actually does not exists at runtime (this is more a way to let Haskell treat the data differently, but the data constructor will be "optimized away"), it makes not much sense.If we compile with:
we can declare the
Money
type as:and Haskell will perform the above derivations for us. This is, to the best of my knowledge, a GHC feature, and thus other Haskell compilers do not per se (well they can of course have this feature) support this.