简体   繁体   English

Haskell:获取数据构造函数名称作为字符串

[英]Haskell: Get data constructor name as string

Let us say we have让我们说我们有

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

I wish to have a function getDConst我希望有一个函数getDConst

getDConst :: D -> String

that returns either "X", "Y", or "Z", according to the data constructor used for its input.根据用于其输入的数据构造函数返回“X”、“Y”或“Z”。 Is there a generic way to write this without having to do case on every data constructor?有没有一种通用的方法来编写这个而不必在每个数据构造函数上做case (I am ok with solutions relying on Data.Typeable or something similar) (我对依赖Data.Typeable或类似的解决方案Data.Typeable

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

If you don't want to use Typeable , you can also do this with Show . 如果您不想使用Typeable ,也可以使用Show执行此操作。

getDConst :: D -> String
getDConst = head . words . show

Show will not output all the fields, because it is lazy. Show不会输出所有字段,因为它很懒。 You can test it runing this code in ghci : 您可以测试它在ghci运行此代码:

Prelude> data D = D [Int] deriving (Show)
Prelude> getDConst $ D [1..]
"D"

I have a much basic answer to the question without going through imports or whatever.我对这个问题有一个非常基本的答案,而无需通过进口或其他任何方式。 It's Just a simple mere function.这只是一个简单的函数。

let's say I have the following data.假设我有以下数据。 The repetitive Int in the data definition is intentional because I will use the don't care symbol afterwards:数据定义中的重复Int是有意的,因为我之后会使用 don't care 符号:

data YES_NO_CANCEL = YES Int | NO Int Int | CANCEL Int Int Int

then you can make a function as :那么你可以创建一个函数:

extractDataType :: YES_NO_CANCEL -> String
extractDataType YES _ = "YES"
extractDataType NO _ _ = "NO".
extractDataType CANCEL _ _ _ = "CANCEL"

. .

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

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