我正在尝试创建一个使用已定义类型的子类型的函数,但 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 但我无法理解该函数,我该如何解决这个问题?
最佳答案
您可以在 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
关于types - OCaml 联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33845651/