# 如何按类型构造函数比较相等值？

## 背景

``````type t = Header | Int(int) | String(string) | Ints(list(int)) | Strings(list(string)) | Footer;
``````

``````/* not equal */
Int(1) == Footer
Int(1) == Int(2)

/* equal */
Int(1) == Int(1)
``````

``````/* equal */
Strings(["Hello", "World"]) == Strings(["Hello", "World"])

/* not equal */
Strings(["Hello", "World"]) == Strings(["a", "b"])
``````

## 题

``````let a = String("a");
let b = String("b");

/* not equal */
a == b

/* for sake of argument, I want to consider all `String(_)` equal, but how? */
``````

``````let equal_tag = (a: 'a, b: 'a) => {
let a = Obj.repr(a);
let b = Obj.repr(b);

switch (Obj.is_block(a), Obj.is_block(b)) {
| (true, true) => Obj.tag(a) == Obj.tag(b)
| (false, false) => a == b
| _ => false
};
};
``````

``````equal_tag(Header, Footer) == false;
equal_tag(String("a"), String("b")) == true;
equal_tag(Int(0), Int(0)) == true;
``````

``````type t =
| A             (* First constant constructor -> integer "Val_int(0)" *)
| B of string   (* First non-constant constructor -> block with tag 0 *)
| C             (* Second constant constructor -> integer "Val_int(1)" *)
| D of bool     (* Second non-constant constructor -> block with tag 1 *)
| E of t * t    (* Third non-constant constructor -> block with tag 2 *)
``````

0 条评论