首页 > 解决方案 > 导出位置显示

问题描述

注意如何T 5显示

> newtype T = T { getT :: Int } deriving Show
> T 5
T {getT = 5}

是否有某种方法可以为使用记录语法声明的类型派生 Show 的位置非记录语法变体?

(顺便说一句T,这只是解释问题的一个简单示例,我正在寻找使用记录语法定义的任何类型的一般答案)

我会满意的一些选项:

对于一个更复杂的例子,我有这个手写的实例

instance ... where
    showsPrec p (FuncType i o) =
        showParen (p > 0)
        (("FuncType " <>) . showsPrec 1 i . (" " <>) . showsPrec 1 o)

我希望答案能够避免这个样板。

标签: haskellmetaprogrammingtypeclasstemplate-haskellderiving

解决方案


手动实现 Show

默认的实现方式Show需要相当多的样板文件。这是由show-combinators处理的,将所需的代码减少到基本要素:

instance Show ... where
  showPrec = flip (\(FuncType i o) -> showCon "FuncType" @| i @| o)

我认为这个解决方案是最简单的。没有扩展,引擎盖下没有类型类魔法。只是简单的函数式编程。

(免责声明:我编写了这篇文章中提到的两个库。)

使用 GHC 泛型

Showin有一个通用实现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-dataunsetIsRecord

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)

推荐阅读