gpt4 book ai didi

haskell - 元组可以有一个特殊的 Show 实例吗?

转载 作者:行者123 更新时间:2023-12-02 21:08:18 24 4
gpt4 key购买 nike

我正在使用所谓的 token ,这些 token 是带有字符串和标签的元组,我希望可以按以下格式在屏幕上呈现它们:[TAG: VALUE] 我不能这样做因为我没有做正确的事情。设置如下:

type Token value tag = ([value], tag)
data Tag = Whitespace | Alpha | Digit | Punctuation | Terminal
instance Show Tag where
show Alpha = "A"
show Whitespace = "W"
show Digit = "D"
show Punctuation = "P"
show Terminal = "|"
type TextToken = Token Char Tag
instance Show TextToken where
show (values, tag) = "[" ++ show tag ++ ": " ++ values ++ "]"

编译时崩溃:

Illegal instance declaration for `Show TextToken'
(All instance types must be of the form (T t1 ... tn)
where T is not a synonym.
Use -XTypeSynonymInstances if you want to disable this.)
In the instance declaration for `Show TextToken'

然后我尝试用以下内容替换实例:

instance Show ([Char], Tag) where
show (values, tag) = "[" ++ show tag ++ ": " ++ values ++ "]"

又遇到同样的问题:

Illegal instance declaration for `Show ([Char], Tag)'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use -XFlexibleInstances if you want to disable this.)
In the instance declaration for `Show ([Char], Tag)'

有办法让它发挥作用吗?

最佳答案

您需要使用新类型

newtype Tag a b = Tag (a, b)

instance (Show a, Show b) => Show (Tag a b) where
show (Tag (a, b)) = "[" ++ show a ++ ": " ++ show b ++ "]"

您同时遇到了多个实例解析问题。

  1. 没有 {-# LANGUAGE TypeSynonymInstances #-} pragma,您不能使用 type实例定义中的同义词......即使它们非常清楚。启用它很好,它根本不是 Haskell 98。

  2. 在实例定义中使用复杂、嵌套或多参数类型时,您经常会与过于严格的 Haskell 98 实例定义发生冲突。在许多情况下,这很好,因此启用 {-# LANGUAGE FlexibleInstances #-} pragma 将允许这些好的机会。

  3. 最后,危险的是,已经有一个 Show ([Char], Tag) 的实例,多态性 instance Show (a, b)a ~ [Char]b ~ Tag 。这意味着您将与 OverlappingInstances 发生冲突。警告。

您可以通过告诉 GHC 允许 OverlappingInstances 来禁用此功能使用另一个编译指示 {-# LANGUAGE OverlappingInstances #-}但由于它可能会给您自己和使用您代码的其他人带来非常奇怪的运行时行为,因此强烈建议不要使用它。

通常,如果您尝试将实例声明“专门化”为特定类型,则需要不存在一般情况。

newtype Tup a b = Tup (a, b)

instance Show (Tup Int Int) where
show (Tup tup) = show tup

instance Show (Tup String Int) where
show (Tup (s, int)) = s ++ ": " ++ show int

>>> show ("foo", 3)
foo: 3
>>> show (2, 3)
(2, 3)
>>> show ("foo", "bar")
No instance for...

关于haskell - 元组可以有一个特殊的 Show 实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19797637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com