模式匹配记录类型

发布于 2024-11-30 09:51:10 字数 500 浏览 1 评论 0原文

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

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

我想创建一个谓词来告诉我给定的 Point 是否位于有效区域中。

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's consider the following Point record type:

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

I'd like to make a predicate that tells me whether a given Point is in a valid region.

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

This works, yet I wonder if there's an alternative way of achieving the same result having as insideBounds signature

let insideBounds {x=i; y=j}

instead, still making use of pattern matching?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寒冷纷飞旳雪 2024-12-07 09:51:10

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

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 成员在指定范围内。活动模式返回选项单元,这意味着它不绑定任何值。 (0, 100) 是输入参数,当值(xy)在范围内时,模式匹配。

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

You can define an active pattern that tests whether a value is inside a range specified as an argument:

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

Then you can define insideBounds like this:

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

The first case matches when both x anad y members are in the specified range. The active pattern returns option unit, which means that it doesn't bind any values. The (0, 100) is an input argument and the pattern matches when the value (x or y) is in the range.

(In other context `match 10 with InRange (0

一念一轮回 2024-12-07 09:51:10

当然。

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

let insideBounds {x=i; y=j} =
  let notInside c = c < 0 || c > 100
  not (notInside i || notInside j)

我建议反转你的逻辑以使其更清晰:

let insideBounds {x=i; y=j} =
  let isInside c = c >= 0 && c <= 100
  isInside i && isInside j

作为一般规则,布尔函数/属性等最好是肯定的。这样,否定就保留了它的否定性,可以这么说。

Sure.

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

let insideBounds {x=i; y=j} =
  let notInside c = c < 0 || c > 100
  not (notInside i || notInside j)

I'd recommend inverting your logic to make it clearer:

let insideBounds {x=i; y=j} =
  let isInside c = c >= 0 && c <= 100
  isInside i && isInside j

As a general rule, it's better for boolean functions/properties, etc to be affirmative. That way, negation retains it's negativity, so to speak.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文