作为一项任务,我必须以一种giveMoney
适当使用的方式实现我的程序的Show类型类,以便将注释更改为最高可能的更改。到目前为止,我知道在使用giveMoney (value [list of notes])
时我可以获得更改列表,但是,当我尝试在当前实现中使用Money [list of notes]
时,我得到了堆栈溢出异常:
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)
答案 0 :(得分:2)
代码存在两个问题。
一旦你做到了这一点,就会抛出这段代码的类型错误:
instance Show Money where
show (Money notes) = giveMoney (value notes)
您可以将代码转换为:
来纠正错误instance Show Money where
show (Money notes) = show $ giveMoney (value notes)
ghci中的演示:
ghci> Money [Ten]
[Ten]