2014-01-18 74 views
1

作爲一項任務,我必須使用giveMoneygiveMoney方式來實現我的程序的Show類型類,以便將註釋更改爲最高可能的更改。到目前爲止,我知道我可以使用giveMoney (value [list of notes])時獲得變化的名單,但是,我得到一個堆棧溢出異常,當我嘗試在我目前的方案中使用Money [list of notes]Haskell:在自定義顯示類型類中的堆棧溢出

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) 

回答

2

有兩個問題碼。

  1. 縮進你的代碼

一旦你做出正確的,它拋出一個錯誤類型爲這個代碼:由代碼轉換爲

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] 
+0

就是這樣,非常感謝。 – dschib