【问题标题】:Haskell: Deriving Show for custom typeHaskell:为自定义类型派生 Show
【发布时间】:2011-05-21 13:38:56
【问题描述】:

我有这个类型定义:

data Operace = Op (Int->Int->Int) String (Int->Int->Int) deriving Show

我想将此类型打印到交互式外壳 (GHCi) 中。应该打印的只是String 字段。

我试过了:

instance Show Operace where
    show (Op op str inv) = show str

但我还是不断地得到

No instance for (Show (Int -> Int -> Int))
  arising from the 'deriving' clause of a data type declaration
Possible fix:
  add an instance declaration for (Show (Int -> Int -> Int))
  or use a standalone 'deriving instance' declaration,
       so you can specify the instance context yourself
When deriving the instance for (Show Operace)

我不想为(Int->Int->Int) 添加Show,我只想打印字符串。

感谢您的帮助!

编辑:

供以后参考,固定版本为:

data Operace = Op (Int->Int->Int) String (Int->Int->Int)

instance Show Operace where
    show (Op _ str _) = str

【问题讨论】:

    标签: haskell show typeclass ghci


    【解决方案1】:

    您所做的实例声明是正确的方法。您似乎忘记从原始 data 声明中删除错误的 deriving 子句。

    data Operace = Op (Int->Int->Int) String (Int->Int->Int)
    
    instance Show Operace where
       show (Op op str inv) = show str
    

    【讨论】:

    • 是的,就是这样,谢谢。我希望它会像在类 C 语言中一样工作,在类定义中声明父类型列表。
    • @mzabsky:这是一种强大的机制,因为您可以为现有类型定义其他类型类实例,而无需触及其定义。
    【解决方案2】:

    你可以导出Show,只需先导入Text.Show.Functions

    【讨论】:

      猜你喜欢
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多