繁体   English   中英

使用GHC.Generics将数据构造函数名称作为字符串

[英]Getting the data constructor name as a string using GHC.Generics

我喜欢以下内容:

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

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

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM