As a task, I have to get the Show typeclass of my program to be implemented in a way that giveMoney
is used appropiately to change the notes to the highest possible change. So far, I know that I can get a list of the change when using giveMoney (value [list of notes])
, however, I get a stack overflow exception when I try to use Money [list of notes]
in my current implementation:
data EuroNote = Five | Ten | Twenty | Fifty | Hundred | TwoHundred | FiveHundred deriving Show
data Money = Money [EuroNote]
value = foldr (+) 0 . map notevalue
notevalue Five = 5
notevalue Ten = 10
notevalue Twenty = 20
notevalue Fifty = 50
notevalue Hundred = 100
notevalue TwoHundred = 200
notevalue FiveHundred = 500
giveMoney euros
| euros >= 500 = [FiveHundred] ++ giveMoney(euros - 500)
| euros >= 200 = [TwoHundred] ++ giveMoney(euros - 200)
| euros >= 100 = [Hundred] ++ giveMoney(euros - 100)
| euros >= 50 = [Fifty] ++ giveMoney(euros - 50)
| euros >= 20 = [Twenty] ++ giveMoney(euros - 20)
| euros >= 10 = [Ten] ++ giveMoney(euros - 10)
| euros >= 5 = [Five]
| euros == 0 = []
instance Show Money where
show (Money notes) = giveMoney (value notes)
There are two problems with the code.
Once you make that correct, it throws a type error for this code:
instance Show Money where
show (Money notes) = giveMoney (value notes)
You can rectify that by converting the code to:
instance Show Money where
show (Money notes) = show $ giveMoney (value notes)
Demo in ghci:
ghci> Money [Ten]
[Ten]