haskell - 导出位置显示
问题描述
注意如何T 5
显示
> newtype T = T { getT :: Int } deriving Show
> T 5
T {getT = 5}
是否有某种方法可以为使用记录语法声明的类型派生 Show 的位置非记录语法变体?
(顺便说一句T
,这只是解释问题的一个简单示例,我正在寻找使用记录语法定义的任何类型的一般答案)
我会满意的一些选项:
- 图书馆为其提供的第 TH 代
- 基于派生(
Generic
手动实例引用现有函数) - 手动实现
Show
实例的简单方法/指南 - 我没有想到的任何其他想法
对于一个更复杂的例子,我有这个手写的实例:
instance ... where
showsPrec p (FuncType i o) =
showParen (p > 0)
(("FuncType " <>) . showsPrec 1 i . (" " <>) . showsPrec 1 o)
我希望答案能够避免这个样板。
解决方案
手动实现 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)
推荐阅读
- python - 左键圆的出现和增加
- reactjs - Formik:获取特定组件的值
- javascript - ajax 调用是否有任何 ES6 等效项?
- amazon-web-services - AWS Service Catalog:产品和应用程序之间有什么区别
- javascript - 在按钮上单击在新选项卡中从服务器打开文件
- c# - 如何使选定的项目独立于其他项目
- flutter - RangeError(索引):无效值:尝试从端点获取数组时只有有效值为 0:1
- facebook - 无法使用图形 API 获取用户的页面列表
- java - 处理数组中插入元素大小的变化
- mono - 使用单声道,父更新和子不更新在春季网络通量中一对多合并父子和子?