OCaml联合类型

时间:2015-11-21 16:15:28

标签: types ocaml

我试图创建一个使用已定义类型的子类型的函数,但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 

类型号也是一个int但是我无法理解这个函数,我怎么能解决这个问题呢?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

您可以在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
相关问题