比较Haskell中两个项的构造函数的一般方法 [英] A general way of comparing constructors of two terms in Haskell
问题描述
pre codeheckConst(Left x)(Left y)= True
checkConst(Right x)(Left y)= False
...
等等而没有真正进行模式匹配,并且可以通过10个构造函数的顺序将其推广到其他类型。有没有一种很好的方法来做到这一点?
您可能正在寻找 Data.Data
模块。如果使用派生的 Data
实例定义数据类型,如下所示:
{ - #LANGUAGE DeriveDataTypeable# - }
import Data.Data
data Foo = Bar1 Int
| Bar2字符串字符串
| Bar3 Double
derived(Data)
然后你可以通过 toConstr
:
> toConstr(Bar1 1)
Bar1
> toConstr(Bar2hellothere)
Bar2
>
这些是类型 Constr
的值,可以因为你可以定义:
checkConst ::(Data g)=> g - > g - > Bool
checkConst xy = toConstr x == toConstr y
得到:
> checkConst(Bar1 10)(Bar1 20)
True
> checkConst(Bar1 10)(Bar3 20)
False
>
Given two terms t1 t2 of some data type, is there some way to check if t1 and t2 start with the same constructor, without doing some exhaustive case or pattern matching over constructors? Like if my type is Either a b, then I want
checkConst (Left x) (Left y) = True
checkConst (Right x) (Left y) = False
...
and so on without actually doing that pattern matching, and in a way that is generalizable to other types with on the order of 10 constructors. Is there a nice way to do this?
You are probably looking for the generics functionality available in the Data.Data
module. If you define a data type with a derived Data
instance, like so:
{-# LANGUAGE DeriveDataTypeable #-}
import Data.Data
data Foo = Bar1 Int
| Bar2 String String
| Bar3 Double
deriving (Data)
then you can retrieve the constructor for a value with toConstr
:
> toConstr (Bar1 1)
Bar1
> toConstr (Bar2 "hello" "there")
Bar2
>
These are values of type Constr
that can be compared for equality, so you can define:
checkConst :: (Data g) => g -> g -> Bool
checkConst x y = toConstr x == toConstr y
and get:
> checkConst (Bar1 10) (Bar1 20)
True
> checkConst (Bar1 10) (Bar3 20)
False
>
这篇关于比较Haskell中两个项的构造函数的一般方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!