我想定义一个类型,以便所有构造都通过可以保留不变量的模块成员,但允许解构以进行模式匹配。
我只是在学习 OCaml,但以下几乎适用于具有左边应该严格小于右边的不变量的 int 对
module Range : sig
type t = private { left:int; right:int }
exception InvalidRange of (int*int)
val make : int -> int -> t
end = struct
type t = { left:int; right:int }
exception InvalidRange of (int*int)
let make left right = if left < right
then { left; right }
else raise (InvalidRange (left, right))
end
这样有效
# let p = Range.make 1 2;;
val p : Range.t = {Range.left = 1; Range.right = 2}
# let q = Range.make 2 1;;
Exception: Range.InvalidRange (2, 1).
和时尚后的解构作品
# let {Range.left=x; Range.right=y} = p;;
val x : int = 1
val y : int = 2
构建失败时
# let badp = {Range.left = 2; Range.right = 1};;
let badp = {Range.left = 2; Range.right = 1};;
Error: Cannot create values of the private type Range.t
# open Range;;
# let badp = {left = 2; right=1};;
let badp = {left = 2; right=1};;
Error: Cannot create values of the private type Range.t
但我真正想做的是具有解构元组的语法便利。以下不起作用:
module Range : sig
type t = private int*int
exception InvalidRange of (int*int)
val make : int -> int -> t
end = struct
type t = int*int
exception InvalidRange of (int*int)
let make left right = if left < right
then (left, right)
else raise (InvalidRange (left, right))
end
但是我不能使用元组模式对其进行解构:
# let r = Range.make 1 2 ;;
val r : Range.t = (1, 2)
# let (a, b) = r;;
let (a, b) = r;;
Error: This expression has type Range.t
but an expression was expected of type 'a * 'b
我可以将类型更改为,type t = R of (int * int)
但我需要这些尽可能轻量级的内存。有任何想法吗?