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

倖福魔咒の 提交于 2019-12-12 13:34:17

问题


I'd like something like the following:

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

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.


回答1:


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

We can do:

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


来源:https://stackoverflow.com/questions/48179380/getting-the-data-constructor-name-as-a-string-using-ghc-generics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!