OCaml:与任何否定匹配

发布于 2024-08-30 15:21:25 字数 273 浏览 1 评论 0原文

有没有办法让模式匹配将我的值与任何负数相匹配?负数是多少并不重要,我只需要与任何负数匹配即可。

我已经用这个简单的代码完成了我想要的事情:

let y = if(n < 0) then 0 else n in   
match y with  
0 -> []  
| _ -> [x] @ clone x (n - 1)

但我想消除该 if 语句,并让它将其作为 match 语句中的另一种情况进行检查

Is there a way to get pattern matching to match my value with any negative number? It does not matter what the negative number is I just need to match with any negative.

I have accomplished what I want with this simple code:

let y = if(n < 0) then 0 else n in   
match y with  
0 -> []  
| _ -> [x] @ clone x (n - 1)

But I want to eliminate that if statement and just get it to check it as another case in the match statement

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

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

发布评论

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

评论(3

雨落□心尘 2024-09-06 15:21:25

是的,使用守卫:

match n with
    _ when n < 0 -> []
  | _ -> [x] @ clone x (n - 1)

Yes, use a guard:

match n with
    _ when n < 0 -> []
  | _ -> [x] @ clone x (n - 1)
从来不烧饼 2024-09-06 15:21:25

您可以使您的代码变得更简洁,如下所示:

match n < 0 with
| true -> []
| false -> [x] @ clone x (n - 1)

更好的是:

if n < 0 then [] else [x] @ clone x (n - 1)

通常,if 语句比简单逻辑测试的匹配更清晰。

当我们这样做时,我们不妨使用 :: 代替 @

if n < 0 then [] else x :: clone x (n - 1)

You can make your code a little cleaner like this:

match n < 0 with
| true -> []
| false -> [x] @ clone x (n - 1)

Even better would be:

if n < 0 then [] else [x] @ clone x (n - 1)

Generally, if statements are clearer than matches for simple logical tests.

While we're at it, we might as well use :: in place of @:

if n < 0 then [] else x :: clone x (n - 1)
指尖上得阳光 2024-09-06 15:21:25

有关键字when。通过头部(我现在无法测试)

让 y = 与 n 匹配
|当 n < 0-> 0
| 0-> []
| _-> [x] @ clone x (n - 1)

但是,即使你的示例也不应该工作。一方面返回一个 int,另一方面返回一个列表。

There is the keyword when. By head (I can't test right now)

let y = match n with
| when n < 0 -> 0
| 0 -> []
| _ -> [x] @ clone x (n - 1)

However, even your example shouldn't work. As on one side you return an int, and on the other a list.

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