创建 Haskell 实例声明
这里对 Haskell 完全是菜鸟,可能还有一个更菜鸟的问题。我正在尝试让 ghci 输出正常工作,但陷入了实例声明。我如何声明“(Show (Stack -> Stack))”的实例:
data Cmd = LD Int
| ADD
| MULT
| DUP
deriving Show
type Prog = [Cmd]
type Stack = [Int]
type D = Stack -> Stack
我一直在尝试创建如下声明:
instance Show D where show = Stack
但我所有的尝试都导致了非法实例声明。非常感谢任何帮助和/或参考!
complete noob to Haskell here with probably an even noobier question. I'm trying to get ghci output working and am stuck on instance declarations. How could I declare an instance for "(Show (Stack -> Stack))" given:
data Cmd = LD Int
| ADD
| MULT
| DUP
deriving Show
type Prog = [Cmd]
type Stack = [Int]
type D = Stack -> Stack
I've been trying to create a declaration like:
instance Show D where show = Stack
but all my attempts have resulted in illegal instance declarations. Any help and/or references much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,默认情况下,类型同义词(即使用
type
定义的内容)在实例声明中是不合法的。不过,有一个 GHC 扩展可以实现这一点。除此之外,在这种特定情况下,
show
需要返回一个String
;您的实例试图返回一个...类型同义词名称,这甚至从一开始就没有意义,而且还引用Int
列表,这是的错误返回类型>显示。
最后,
D
是一个函数类型——它应该显示
什么呢?在大多数情况下,对于函数类型的Show
实例,您实际上无法做太多有意义的事情。如果您只想说“这是 D 型”,您可以编写这样的实例:
不过,我不确定这在实践中有多有用。
First of all, by default, type synonyms (that is, stuff defined using
type
) aren't legal in instance declarations. There's a GHC extensions to allow this, however.Beyond that, in this specific case,
show
needs to return aString
; your instance is trying to return a... type synonym name, which doesn't even make sense to begin with, and besides refers to a list ofInt
, which is the wrong return type forshow
.Finally,
D
is a function type--what is that supposed toshow
, anyway? There's really not much you can meaningfully do with aShow
instance on a function type, in most cases.If you just want it to say "this is type D", you could write an instance like this:
I'm not sure how useful that is in practice, though.