gpt4 book ai didi

.net - 模式匹配记录类型

转载 作者:行者123 更新时间:2023-12-01 05:25:07 26 4
gpt4 key购买 nike

让我们考虑以下 Point 记录类型:

type Point = { x:int; y:int }

我想做一个谓词来告诉我给定点是否在有效区域中。

let insideBounds p =
let notInside c = c < 0 || c > 100
match p with
| {x=i; y=_} when notInside i -> false
| {x=_; y=j} when notInside j -> false
| _ -> true

这行得通,但我想知道是否有另一种方法可以实现与 insideBounds 签名相同的结果

let insideBounds {x=i; y=j}

相反,仍然使用模式匹配?

最佳答案

您可以定义一个事件模式来测试一个值是否在指定为参数的范围内:

let (|InRange|_|) (min, max) v = 
if v >= min && v <= max then Some () else None

然后你可以这样定义insideBounds:

let insideBounds = function
| { x = InRange (0, 100); y = InRange (0, 100) } -> true
| _ -> false

xy 成员都在指定范围内时,第一种情况匹配。事件模式返回 option unit,这意味着它不绑定(bind)任何值。 (0, 100) 是一个输入参数,当值(xy)在范围内时模式匹配。

(在其他上下文中`将 10 与 InRange (0

关于.net - 模式匹配记录类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7110179/

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