OCaml 联合类型

OCaml union types

我正在尝试创建一个使用已定义类型的子类型的函数,但 OCaml 不会派生出正确的值: 考虑这个类型定义:

type fraction = {numerator : int; denominator : int};;

type number =
  | Int of int
  | Fraction of fraction;;

如果我尝试输入 interpeter(如果重要的话,我正在使用 utop):

utop # ((fun a-> a>0) (Int 1));;
Error: This expression has type number but an expression was expected of type int 

type number 也是一个 int 但我无法理解这个函数,我该如何解决这个问题?

a>0 中的 0 是一个 int,因此这是函数期望作为参数的类型。您可能想要的是 0 等效于 number,如下所示:

# (fun a -> a > Int 0) (Int 1)
- : bool = true

您可以在 fun:

中使用模式匹配
# (fun (Int a) -> a > 0) (Int 1);;
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
Fraction _
- : bool = true

显然,如果您传入 Fraction,这将引发匹配错误。如果你想处理这种情况:

# (function Int a -> a > 0 | Fraction {numerator = a; denominator = b}  -> a/b > 0 ) (Int 1);;
- : bool = true