haskell - 为什么这个 Haskell 代码会产生堆栈溢出?

标签 haskell stack-overflow

我是第一次玩 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/

相关文章:

haskell - 如何在 IHP 中自定义 404?

haskell - Applicative 的 ghci 特例?

java - 优化 N Queens 代码以避免堆栈溢出

c - 指针初始化字符串文字

java - 哈希表中的冲突解决

haskell - 将函数定义更改为无点样式

haskell - monads current "state of the art"是用纯语言做 IO 吗?

haskell - VTY-UI需要IO。我能让这件事发生吗?

java - 类构造函数中的堆栈溢出错误

C++ 二叉树堆栈溢出