Haskell:获取数据构造函数名称为字符串 [英] Haskell: Get data constructor name as string

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

问题描述

让我们说我们拥有

data D = X Int | Y Int Int | Z String

我希望有一个功能getDConst

getDConst :: D -> String

根据用于其输入的数据构造函数返回"X","Y"或"Z".有没有一种通用的方法可以编写此代码而不必在每个数据构造函数上执行case? (我可以使用依赖Data.Typeable或类似方法的解决方案)

that returns either "X", "Y", or "Z", according to the data constructor used for its input. Is there a generic way to write this without having to do case on every data constructor? (I am ok with solutions relying on Data.Typeable or something similar)

推荐答案

我自己找到了解决方案,但留下了这个问题来帮助其他人:

Found the solution myself, but leaving this question to help others:

import Data.Data
data D = X Int | Y Int Int deriving (Data,Typeable)

let result = show $ toConstr (X 3) -- result contains what we wanted

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

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