使用GHC.Generics获取数据构造函数名称作为字符串 [英] Getting the data constructor name as a string using GHC.Generics

查看:66
本文介绍了使用GHC.Generics获取数据构造函数名称作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要以下内容:

constrName :: Data a=> a -> String
constrName = showConstr . toConstr

但对于GHC.Generics.我看到了Constructor类,但是没有看到范围内的任何实例.我正在使用base-4.8.1.0.

But for GHC.Generics. I see the Constructor class, but don't see any instances in scope. I'm using base-4.8.1.0.

推荐答案

Nathan Howell修改的要点: https ://gist.github.com/NathanHowell/6201625 :

Adapting this gist by Nathan Howell: https://gist.github.com/NathanHowell/6201625 :

{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}

import GHC.Generics

constrName :: (HasConstructor (Rep a), Generic a)=> a -> String
constrName = genericConstrName . from 

class HasConstructor (f :: * -> *) where
  genericConstrName :: f x -> String

instance HasConstructor f => HasConstructor (D1 c f) where
  genericConstrName (M1 x) = genericConstrName x

instance (HasConstructor x, HasConstructor y) => HasConstructor (x :+: y) where
  genericConstrName (L1 l) = genericConstrName l
  genericConstrName (R1 r) = genericConstrName r

instance Constructor c => HasConstructor (C1 c f) where
  genericConstrName x = conName x

--------------
data Foo = Bar Int | Baz Float deriving Generic
newtype X = X Char deriving Generic
data Y = Y deriving Generic

我们可以做到:

*Main> constrName (Bar 1)
"Bar"
*Main> constrName $ X 'a'
"X"
*Main> constrName Y
"Y"

这篇关于使用GHC.Generics获取数据构造函数名称作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆