我是第一次玩 Haskell。我写了这三行,希望得到一个编译器错误,但在 ghci
中输入了它导致堆栈溢出。
$ ghci
GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> data ImNewToHaskell = AndWhatIsThis
Prelude> instance Show ImNewToHaskell
Prelude> show AndWhatIsThis
"*** Exception: stack overflow
谁能解释这种行为?
最佳答案
您没有定义实例的方法。 show
的默认值使用 showPrec
(通过 shows
)和 showPrec
的默认值使用 show
.所以你有一个循环定义,它最终会明显溢出堆栈。也许您打算派生一个实例?
Prelude> data ImNewToHaskell = AndWhatIsThis deriving (Show)
Prelude> show AndWhatIsThis
"AndWhatIsThis"
编辑:清除
instance
的任何问题和 deriving
:当您键入
instance
is 表示“我将定义自己的实例或利用类型类的默认代码”:instance Show Foo where
show Foo = "This is the string representing Foo"
当您键入
deriving
在数据声明之后,编译器将自动为您的类型生成一个合理的实例:data MyType = OneOrMoreConstructors deriving (Show)
如果您或其他程序员没有派生所需的实例并且您不想编写自己的实例,那么您可以使用独立派生,这会产生与使用
deriving
相同的结果但在不同的模块中可能在它自己的线上:{-# LANGUAGE StandaloneDeriving #-}
deriving instance Show MyType
关于haskell - 为什么这个 Haskell 代码会产生堆栈溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29054898/