Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

overriding - Accessing the "default show" in Haskell?

Say you have a data-structure (borrowed from this question):

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

Now one can make it an instance of Show by appending deriving Show on that instruction.

Say however we wish to show Number Int as:

instance Show Greek where
    show (Number x) = show x
    -- ...

The problem is that one must specify all other parts of the Greek data as well like:

    show Alpha = "Alpha"
    show Beta = "Beta"

For this small example that's of course doable. But if the number of options is long, it requires a large amount of work.

I'm wondering whether it is possible to access the "default show" implementation and call it with a wildcard. For instance:

instance Show Greek where
    show (Number x) = show x
    show x = defaultShow x

You thus "implement" the specific patterns that differ from the default approach and the remaining patterns are resolved by the "fallback mechanism".

Something a bit similar to method overriding with a reference to super.method in object oriented programming.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As @phg pointed above in comment this can be also done with help of 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...