gpt4 book ai didi

pattern-matching - 在允许解构的同时保留不变量

转载 作者:行者123 更新时间:2023-12-04 13:11:59 25 4
gpt4 key购买 nike

我想定义一个类型,以便所有构造都通过可以保留不变量的模块成员,但允许解构以进行模式匹配。

我只是在学习 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)但我需要这些尽可能轻量级的内存。有任何想法吗?

最佳答案

manual 中所述,你需要一个明确的强制:

# let (a, b) = (r :> int*int);;
val a : int = 1
val b : int = 2

关于pattern-matching - 在允许解构的同时保留不变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10709992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com