假设我们有
data People a = Person { name::a , age::Int} deriving Show
在我打字时拥抱
> Person "Alihuseyn" 20
我得到Person {name = "Alihuseyn", age = 20}
但我想得到Person Person "Alihuseyn" 20
。
我的意思是如何在不更改数据的情况下隐藏姓名和年龄的提及?
假设我们有
data People a = Person { name::a , age::Int} deriving Show
在我打字时拥抱
> Person "Alihuseyn" 20
我得到Person {name = "Alihuseyn", age = 20}
但我想得到Person Person "Alihuseyn" 20
。
我的意思是如何在不更改数据的情况下隐藏姓名和年龄的提及?
如果需要,您始终可以Show
为所有类型提供自定义实例:
data People a = Person { name::a , age::Int}
instance (Show a) => Show (People a) where
show (Person name age) == "Person " ++ show name ++ " " ++ show age
或者,或者不太优雅,编写自定义访问器:
data People a = Person a Int deriving Show
name (Person n _) = n
age (Person _ a) = a
无论哪种方式,您都必须更改 的声明People
,否则您将陷入派生Show
实例。
附带说明,如果您有一个只有一个构造函数的数据类型,您通常在类型之后命名构造函数,所以它是data Person a = Person { name :: a, age :: Int }
这用于GHC.Generics
提供一个showsPrecDefault
,可以很容易地用来定义一个Show
实例。
data Person a = Person { name :: a, age :: Int } deriving Generic
instance Show a => Show (Person a) where showsPrec = showsPrecDefault
>>> Person "Alihuseyn" 20
Person "Alihuseyn" 20
的定义showsPrecDefault
如下。
{-# LANGUAGE
DeriveGeneric
, FlexibleContexts
, FlexibleInstances
, KindSignatures
, TypeOperators
, TypeSynonymInstances #-}
import GHC.Generics
class GShow f where
gshowsPrec :: Int -> f a -> ShowS
instance GShow U1 where
gshowsPrec _ U1 = id
instance Show c => GShow (Rec0 c) where
gshowsPrec p = showsPrec p . unK1
instance GShow f => GShow (D1 d f) where
gshowsPrec p = gshowsPrec p . unM1
instance Constructor c => GShow (C1 c U1) where
gshowsPrec _ c@(M1 U1) = showParen (isInfix c) (showString (conName c))
instance (Constructor c, GShow (M1 i c f)) => GShow (C1 c (M1 i c f)) where
gshowsPrec = gshowsPrec'
instance (Constructor c, GShow (f :+: g)) => GShow (C1 c (f :+: g)) where
gshowsPrec = gshowsPrec'
instance (Constructor c, GShow (f :*: g)) => GShow (C1 c (f :*: g)) where
gshowsPrec = gshowsPrec'
gshowsPrec' :: (Constructor c, GShow f) => Int -> C1 c f p -> ShowS
gshowsPrec' p c@(M1 f) =
showParen (p > 10) $
showParen (isInfix c) (showString (conName c)) .
showChar ' ' .
gshowsPrec 11 f
isInfix :: Constructor c => t c (f :: * -> *) a -> Bool
isInfix c = case conFixity c of
Infix _ _ -> True
_ -> False
instance GShow f => GShow (S1 s f) where
gshowsPrec p = gshowsPrec p . unM1
instance (GShow a, GShow b) => GShow (a :+: b) where
gshowsPrec p (L1 a) = gshowsPrec p a
gshowsPrec p (R1 b) = gshowsPrec p b
instance (GShow a, GShow b) => GShow (a :*: b) where
gshowsPrec p (a :*: b) =
gshowsPrec (p + 1) a .
showChar ' ' .
gshowsPrec (p + 1) b
showsPrecDefault :: (Generic a, GShow (Rep a)) => Int -> a -> ShowS
showsPrecDefault p = gshowsPrec p . from