创建 Haskell 实例声明

发布于 2024-08-30 10:58:34 字数 407 浏览 4 评论 0原文

这里对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

栖竹 2024-09-06 10:58:34

首先,默认情况下,类型同义词(即使用 type 定义的内容)在实例声明中是不合法的。不过,有一个 GHC 扩展可以实现这一点。

除此之外,在这种特定情况下,show 需要返回一个String;您的实例试图返回一个...类型同义词名称,这甚至从一开始就没有意义,而且还引用 Int 列表,这是 的错误返回类型>显示。

最后,D 是一个函数类型——它应该显示什么呢?在大多数情况下,对于函数类型的 Show 实例,您实际上无法做太多有意义的事情。

如果您只想说“这是 D 型”,您可以编写这样的实例:

{-# LANGUAGE TypeSynonymInstances #-}
instance Show D where show _ = "Stack -> Stack"

不过,我不确定这在实践中有多有用。

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 a String; 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 of Int, which is the wrong return type for show.

Finally, D is a function type--what is that supposed to show, anyway? There's really not much you can meaningfully do with a Show 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:

{-# LANGUAGE TypeSynonymInstances #-}
instance Show D where show _ = "Stack -> Stack"

I'm not sure how useful that is in practice, though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文