OCaml:与任何否定匹配
有没有办法让模式匹配将我的值与任何负数相匹配?负数是多少并不重要,我只需要与任何负数匹配即可。
我已经用这个简单的代码完成了我想要的事情:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,使用守卫:
Yes, use a guard:
您可以使您的代码变得更简洁,如下所示:
更好的是:
通常,if 语句比简单逻辑测试的匹配更清晰。
当我们这样做时,我们不妨使用
::
代替@
:You can make your code a little cleaner like this:
Even better would be:
Generally, if statements are clearer than matches for simple logical tests.
While we're at it, we might as well use
::
in place of@
:有关键字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.