OCaml 多态变体:在多个匹配模式中绑定相同的名称

OCaml polymorphic variants: bind the same name in multiple match patterns

我不确定标题是否解释得很好,但这是一个具体的例子:我有一个形状的多态变体,以及一个 print_round 函数,它可以作用于这些变体的一个子集(圆的):

type round_shape = [
    | `oval of int * int
    | `circle of int
]

type shape = [
    | round_shape
    | `rectangle of int * int
]

let print_round : round_shape -> unit = function
    | `oval (width, height) -> failwith "todo"
    | `circle radius -> failwith "todo"

现在,这个函数编译:

let print_shape : shape -> unit = function
    | `rectangle _ -> failwith "TODO"
    | `oval _ as round -> print_round round
    | `circle _ as round -> print_round round

但这似乎是重复的 - 这是我想要编写的代码:

let print_shape = function
    | `rectangle -> failwith "TODO"
    | `oval _ as round | `circle _ as round -> print_round round

使用该代码,我得到:

Error: Variable round must occur on both sides of this | pattern

我就是不明白。显然 round 确实出现在两边。我怎样才能让它在最后一个分支中将 round 绑定为 round_shape,并使用最少的类型转换?

您需要的模式语法是

pattern_1 | pattern_2 ... | pattern_n as name

可以找到模式语法here。考虑到这一点,我们得到

let print_shape = function
    | `rectangle -> failwith "TODO"
    | `oval _ | `circle _ as round -> print_round round