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

时间:2016-09-24 13:03:16

标签: pattern-matching ocaml

我不确定标题是否能很好地解释它,但这里有一个具体的例子:我有一个形状的多态变体,以及一个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

使用该代码,我得到:

  

错误:必须在此|的两侧进行变量舍入图案

我不明白。很明显round确实出现在双方身上。如何才能将round作为round_shape绑定到最后一个分支中,并使用最少的类型转换?

1 个答案:

答案 0 :(得分:1)

您需要的模式语法是

pattern_1 | pattern_2 ... | pattern_n as name

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

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