比较Haskell中两个项的构造函数的一般方法 [英] A general way of comparing constructors of two terms in Haskell

查看:119
本文介绍了比较Haskell中两个项的构造函数的一般方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个t1 t2的某些数据类型,是否有一些方法可以检查t1和t2是否以相同的构造函数开始,而不对构造函数做一些详尽的案例或模式匹配?如果我的类型是ab或者ab,那么我想要

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屋!

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