types - OCaml 联合类型

标签 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 

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/

相关文章:

c# - 我应该如何将 SqlXml 转换为 XmlText?

haskell - 与分数相关的类型错误

functional-programming - 函数式语言中的质因数分解

arrays - 如何打印数组数组?

ocaml - 使用千位分隔符格式化数字

types - 如何将 OCaml 整数类型限制为整数范围?

javascript - 在 TypeScript 中将类型作为变量返回

types - 使用带有可选参数的打印机输入格式

ocaml - 从显式 token 列表中输入 ocamlyacc 解析器?

lambda - 为什么`id id`在OCaml中不是值?