手动实现 Show
默认的实现方式Show
需要相当多的样板文件。这是由show-combinators处理的,将所需的代码减少到基本要素:
instance Show ... where
showPrec = flip (\(FuncType i o) -> showCon "FuncType" @| i @| o)
我认为这个解决方案是最简单的。没有扩展,引擎盖下没有类型类魔法。只是简单的函数式编程。
(免责声明:我编写了这篇文章中提到的两个库。)
使用 GHC 泛型
Show
in有一个通用实现generic-data
:(链接到源代码gshowsPrec
)。但它将使用记录语法声明的类型显示为记录。
重做实现
一种方法当然是复制实现并删除对记录的特殊处理。
{- 1. The usual boilerplate -}
class GShow p f where
gPrecShows :: p (ShowsPrec a) -> f a -> PrecShowS
instance GShow p f => GShow p (M1 D d f) where
gPrecShows p (M1 x) = gPrecShows p x
instance (GShow p f, GShow p g) => GShow p (f :+: g) where
gPrecShows p (L1 x) = gPrecShows p x
gPrecShows p (R1 y) = gPrecShows p y
{- 2. A simplified instance for (M1 C), that shows all constructors
using positional syntax. The body mostly comes from the instance
(GShowC p ('MetaCons s y 'False) f). -}
instance (Constructor c, GShowFields p f) => GShow p (M1 C c f) where
gPrecShows p x = gPrecShowsC p (conName x) (conFixity x) x
where
gPrecShowsC p name fixity (M1 x)
| Infix _ fy <- fixity, k1 : k2 : ks <- fields =
foldl' showApp (showInfix name fy k1 k2) ks
| otherwise = foldl' showApp (showCon cname) fields
where
cname = case fixity of
Prefix -> name
Infix _ _ -> "(" ++ name ++ ")"
fields = gPrecShowsFields p x
型手术
(以我的博文命名的部分,但这个线程的情况要简单得多。)
另一种方法是转换我们类型的通用表示,以假装它没有使用记录语法声明。幸运的是,唯一的区别在于幻像类型参数,因此转换可以像coerce
在运行时一样简单。
unsetIsRecord ::
Coercible (f p) (UnsetIsRecord f p) => Data f p -> Data (UnsetIsRecord f) p
unsetIsRecord = coerce
-- UnsetIsRecord defined at the end
newtype基本上是从泛型表示Data
中创建数据类型(Generic
在某种意义上,这与所做的相反)。我们可以将通常声明的类型映射到Data
使用toData :: a -> Data (Rep a) p
.
最后,我们可以直接将库中的gshowsPrec
函数应用到.generic-data
unsetIsRecord
instance Show T where
showsPrec n = gshowsPrec n . unsetIsRecord . toData
UnsetIsRecord
理想情况下应该是 in generic-data
,但由于它还没有,这里有一个可能的实现:
type family UnsetIsRecord (f :: * -> *) :: * -> *
type instance UnsetIsRecord (M1 D m f) = M1 D m (UnsetIsRecord f)
type instance UnsetIsRecord (f :+: g) = UnsetIsRecord f :+: UnsetIsRecord g
type instance UnsetIsRecord (M1 C ('MetaCons s y _isRecord) f) = M1 C ('MetaCons s y 'False) f)