haskell - 在 Haskell 中访问 "default show"?

标签 haskell overriding typeclass

假设您有一个数据结构(借自 question ):

data Greek = Alpha | Beta | Gamma | Delta | Eta | Number Int

现在可以使它成为 Show 的实例。通过附加 deriving Show在那条指令上。

说但是我们希望显示Number Int作为:
instance Show Greek where
    show (Number x) = show x
    -- ...

问题是必须指定Greek 的所有其他部分。数据以及:
    show Alpha = "Alpha"
    show Beta = "Beta"

对于这个小例子,这当然是可行的。但是如果选项的数量很长,则需要大量的工作。

我想知道是否可以访问“默认显示”实现并使用通配符调用它。例如:
instance Show Greek where
    show (Number x) = show x
    show x = defaultShow x

因此,您“实现”了与默认方法不同的特定模式,其余模式由“回退机制”解决。

有点类似于引用 super.method 的方法覆盖。在面向对象编程中。

最佳答案

正如@phg 在评论中指出的那样,这也可以在 generic-deriving 的帮助下完成。 :

{-# LANGUAGE DeriveGeneric #-}
module Main where

import           Generics.Deriving.Base (Generic)
import           Generics.Deriving.Show (GShow, gshow)

data Greek = Alpha | Beta | Gamma | Delta | Eta | Number Int
  deriving (Generic)

instance GShow Greek
instance Show Greek where
  show (Number n) = "n:" ++ show n
  show l = gshow l

main :: IO ()
main = do
  print (Number 8)
  print Alpha

关于haskell - 在 Haskell 中访问 "default show"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28665917/

相关文章:

performance - haskell /GHC : Unsafely deconstruct a constructor?

haskell - 如何在WinGHCi中运行此haskell程序?

css - 无法覆盖字体大小 :100% & font-inherit property in another CSS file

c# - 强制从派生类外部调用基方法

haskell - 是否可以在父类(super class)约束中引入额外的类型变量?

scala - 为什么会发生这种隐含的歧义行为?

haskell - 偶数索引上列表的重复元素

haskell - Haskell 中 websocket 的 "real server"是什么?

c++ - 从 C++ 中的基调用潜在 child 的构造函数

list - unzip的概括是什么?