为什么Haskell中的Show实例(拥抱)导致堆栈溢出错误? [英] Why does this Show instance in Haskell (Hugs) cause a stack overflow error?
问题描述
$ b 实例声明说如果在Show中有一个类型a,那么Equality a在Show中。它应该以a = b的形式将两个参数打印到构造函数Equals ab中。
数据Equality a = Equals aa
instance(显示a)=>显示(平等a)其中
显示(等于ab)= a ++=++ b
然而,在Hugs中输入(Equality 9 9)这样的结果会产生:
$ b $错误 - C堆栈溢出
所以,我尝试用几个空格缩进show(Equals ab)...行。我不确定会有什么区别,但只是玩弄,然后得到这个:
推断类型不是一般的足够
***表达式:show
***预期类型:Show(Equality a)=>平等 - >字符串
***推断类型:Show(Equality [Char])=>平等[Char] - >字符串
任何人都可以解释为什么会出现这些错误,或者建议实现此show实例的更好方法?
谢谢!
解决方案奇怪的空白敏感度。如果没有缩进,编译器无法确定以下语句属于其中
。
错误因为没有约束的多态类型不能确保 a
和 b
可以与= 字符串。如果您有等于1 1
,该怎么办?如何在不使Ints字符串第一次连接的情况下进行连接?
然而,如果
数据Equality a = Equa aa
instance(显示a)=>显示(平等a)其中
显示(等于ab)=(显示a)++=++(显示b)
The following is a polymorphic data type in Haskell, interpreted by Hugs. I am trying to create an instance of Show for Equality.
The instance declaration says that if a type "a" is in Show, then Equality a is in Show. It should print the two arguments to the constructor Equals a b in the form "a = b".
data Equality a = Equals a a
instance (Show a) => Show (Equality a) where
show (Equals a b) = a ++ " = " ++ b
Yet, typing something into Hugs like "(Equality 9 9)" yields:
ERROR - C stack overflow
So, I tried indenting the "show (Equals a b)..." line with a couple of spaces. I'm not sure what the difference would be, but was just playing around and then got this:
Inferred type is not general enough
*** Expression : show
*** Expected type : Show (Equality a) => Equality a -> String
*** Inferred type : Show (Equality [Char]) => Equality [Char] -> String
Can anyone explain why these errors are occurring, or suggest a better way of implementing this show instance?
Thank you!
The indenting does matter due to Haskell's at-times-strange whitespace sensitivity. Without the indent, the compiler cannot tell that the following statement belongs to the where
.
The error that you are getting is because the polymorphic type, having no constraints, does not ensure that a
and b
can concatenated with the " = " string. What if you have Equals 1 1
. How would you concatenate that without making the Ints strings first?
However, if you show
a and b first, all works out because show
martials the values into something that can be concatenated with a String.
data Equality a = Equals a a
instance (Show a) => Show (Equality a) where
show (Equals a b) = (show a) ++ " = " ++ (show b)
这篇关于为什么Haskell中的Show实例(拥抱)导致堆栈溢出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!