#パターン
http://jijixi.azito.com/cgi-bin/diary/index.rb?date=20060622#p06
あれ?これexception使わなくても書けるような。
調べてみたら、#なんていうパターンがあった。
# type t = [`a of a | `b of b | ... `z of z]
みたいなtがあるときに、
# match x with | #t as t -> f t | `aa a -> g a;;
として、
# match x with (`a _ | `b _ | ... | `z _) as t -> f t | `aa a -> g a
の代わりにできるんだとか。
で、書き直してみた。
# type num = [`int of int | `float of float];; type num = [ `float of float | `int of int ] # let (+) x y = match (x,y) with | (`int i, `int j) -> `int (i+j) | (`float f, `float g) -> `float (f +. g);; Warning P: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: (`float _, `int _) val ( + ) : [< `float of float | `int of int ] -> [< `float of float | `int of int ] -> [> `float of float | `int of int ] = <fun> # type str = [ num | `string of string];; type str = [ `float of float | `int of int | `string of string ] # let (+) x y = match (x,y) with ((#num as a), (#num as b)) -> a + b | (`string s, `string t) -> `string(s^t);; Warning P: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: (`string _, (`float _|`int _)) val ( + ) : [< `float of float | `int of int | `string of string ] -> [< `float of float | `int of int | `string of string ] -> [> `float of float | `int of int | `string of string ] = <fun>
めでたしめでたし。
ついでに、[> `float of ... ]みたいな型も消えました。