如何检查是否使用相同的构造函数创建了两个值? [英] How to check whether two values are created with the same constructor?

查看:98
本文介绍了如何检查是否使用相同的构造函数创建了两个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有

type t = A of int | B of int

let xx = A(2);;
let yy = A(3);;

,我想测试xx和yy的构造函数是否相等, 是否有捷径可寻 ?不必

and I want to test if the constructors of xx and yy are equal, is there an easy way to do this ? Instead of having to

match xx with
  A _ ->
  (match yy with A _ -> true | B _ -> false)
| B _ -> 
  (match yy with A _ -> false | B _ -> true);;

当一个类型上有很多构造函数时,它会变得很杂乱

which gets quite messy when there many constructors on a type

推荐答案

您可以将上面的内容重写为更简单的内容:

You can rewrite the above to, somewhat simpler:

match xx, yy with
| A _, A _
| B _, B _ -> true
| (A _ | B _), _ -> false

但是如果不枚举所有构造函数,我不知道有什么解决方案.

but I'm not aware of a solution without enumerating all the constructors.

这篇关于如何检查是否使用相同的构造函数创建了两个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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