2016-09-24 5 views
1

タイトルがうまく説明できるかどうかはわかりませんが、具体的な例があります:図形の多型があり、print_round関数があります。これらの変種(丸いもの)のサブセット:OCaml多型:複数の一致パターンで同じ名前を結びつける

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が表示されます。どのようにしてこのタイプの最後のブランチにroundround_shapeとしてバインドして、最小限の型キャスティングでこれを動作させることができますか?

+0

あなたのコードは '' |あなたの意図としてではなく、 'round | as round |'としての楕円_ ( 'oval _ as round)| ( 'circle _ as round)' ' – camlspotter

答えて

1

あなたが必要とするパターンの構文は

pattern_1 | pattern_2 ... | pattern_n as name 

あるパターン文法はhereを見つけることができます。それを考慮に入れて

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

ああ、完璧です。私は '|'より優先順位が低いとは考えていませんでした。 – gfxmonk

関連する問題