Performing algebra with newtypes based on integers Haskell

后端 未结 2 1894
太阳男子
太阳男子 2021-01-14 02:08

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 p

2条回答
  •  既然无缘
    2021-01-14 02:55

    You're missing a instance of how your money can add together, the clue was in the error Instance : Num Money.

    So for addition in Haskell the Num type what is needed to add two things together as long you are dealing with numbers so let's make an instance of Num on Money:

    newtype Money =
      Money Integer deriving Show
    
    instance Num Money where
      Money a + Money b = Money $ a + b
    
    -- Money 1 + Money 2 == Money 3
    

    Notice that it returns Money, will let you research how you can get the number out of the type :)

提交回复
热议问题