OCaml联合类型

4
我正在尝试编写一个函数,使用已定义类型的子类型,但OCaml无法推导出正确的值: 考虑下面的类型定义:
type fraction = {numerator : int; denominator : int};;

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

如果我尝试在解释器中输入文字(我正在使用utop,如果有关系的话):
utop # ((fun a-> a>0) (Int 1));;
Error: This expression has type number but an expression was expected of type int 

"type number" 也是一个整数,但我无法让函数理解这一点,我该怎么解决?
2个回答

2

a>0中的0是一个int类型,所以函数期望该参数是这种类型。你可能想要的是将0转化为等价的number类型,像这样:

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

不,我想要获取其中的整数,因为我需要它来创建一个分数,但它在一个“数字”类型内部。我将获得一个“数字”列表,并且我需要将其转换为分数,但我不知道如何获取内部的整数值。 - yair
那么你会想要在number上进行模式匹配。 - gsg

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接