模式匹配记录类型
让我们考虑以下 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以定义一个活动模式来测试一个值是否在指定为参数的范围内:
然后您可以像这样定义
insideBounds
:当两个
>x
和y
成员在指定范围内。活动模式返回选项单元
,这意味着它不绑定任何值。(0, 100)
是输入参数,当值(x
或y
)在范围内时,模式匹配。(在其他上下文中`将 10 与 InRange (0
You can define an active pattern that tests whether a value is inside a range specified as an argument:
Then you can define
insideBounds
like this:The first case matches when both
x
anady
members are in the specified range. The active pattern returnsoption 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
ory
) is in the range.(In other context `match 10 with InRange (0
当然。
我建议反转你的逻辑以使其更清晰:
作为一般规则,布尔函数/属性等最好是肯定的。这样,否定就保留了它的否定性,可以这么说。
Sure.
I'd recommend inverting your logic to make it clearer:
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.