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
Moneys, since you never specified how to do that. In order to add up twoas, theas should implement theNumtypeclass. In factnewtypes are frequently used to specify different type instances, for exampleSumandProductare 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 -> ais a member of theFractionaltypeclass, this will give some problems, since yourMoneywraps anIntegerobject.You can however implement the
Integraltypeclass such that it supportsdiv. In order to do this, we however need to implement theRealandEnumtypeclass. TheRealtypeclass requires the type to be implement theOrd, and since theOrdtypeclass requires the object to be an instance of theEqtypeclass, we thus end up implementing theEq,Ord,RealandEnumtypeclass.GeneralizedNewtypeDerivingAs @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
newtypeactually 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
Moneytype 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.