Types OCaml联合类型
我试图创建一个使用已定义类型的子类型的函数,但OCaml无法派生正确的值: 考虑这种类型定义:Types OCaml联合类型,types,ocaml,Types,Ocaml,我试图创建一个使用已定义类型的子类型的函数,但OCaml无法派生正确的值: 考虑这种类型定义: type fraction = {numerator : int; denominator : int};; type number = | Int of int | Fraction of fraction;; 如果我尝试在interpeter中键入(如果有必要,我将使用utop): 类型number也是一个int,但我无法让函数理解,如何解决这个问题?在a>0中的0是一个int,因此这
type fraction = {numerator : int; denominator : int};;
type number =
| Int of int
| Fraction of fraction;;
如果我尝试在interpeter中键入(如果有必要,我将使用utop):
类型number也是一个int,但我无法让函数理解,如何解决这个问题?在
a>0
中的0
是一个int
,因此这是函数期望作为参数的类型。您可能希望0
成为等效的数字,如下所示:
# (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
显然,如果您传入一个分数
,这将引发匹配错误。如果您想处理该案件:
# (function Int a -> a > 0 | Fraction {numerator = a; denominator = b} -> a/b > 0 ) (Int 1);;
- : bool = true
不,我想得到里面的整数,我以后需要它来创建一个分数,但是它在一个“数字”类型中,我要得到一个“数字”列表,我需要把它变成一个分数,但是我不知道如何得到里面的整数值,你需要在数字上进行模式匹配。
# (function Int a -> a > 0 | Fraction {numerator = a; denominator = b} -> a/b > 0 ) (Int 1);;
- : bool = true