List Haskell:自定义Show typeclass中的堆栈溢出

List Haskell:自定义Show typeclass中的堆栈溢出,list,exception,haskell,stack-overflow,typeclass,List,Exception,Haskell,Stack Overflow,Typeclass,作为一项任务,我必须以适当使用giveMoney的方式实现我的程序的Show-typeclass,以将注释更改为可能的最大更改。到目前为止,我知道在使用giveMoney(value[list of notes])时可以获得更改列表,但是,在我当前的实现中尝试使用Money[list of notes]时,会出现堆栈溢出异常: data EuroNote = Five | Ten | Twenty | Fifty | Hundred | TwoHundred | FiveHundred

作为一项任务,我必须以适当使用
giveMoney
的方式实现我的程序的Show-typeclass,以将注释更改为可能的最大更改。到目前为止,我知道在使用
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)

代码有两个问题

  • 用代码缩进
  • 一旦您纠正了错误,它将抛出此代码的类型错误:

    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]