OCaml:模式匹配与 If/else 语句
因此,我对 OCaml 完全陌生,并且在实现第一个功能方面进展相当缓慢。我难以理解的一件事是何时使用模式匹配功能,例如
let foo =
[] -> true
| _ -> false;;
vs 使用 if else 结构,例如
let foo a =
if a = [] then true else false;;
我应该何时使用每个功能?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为这个问题没有明确的答案。首先,模式匹配的明显情况是当您需要解构时,例如:
另一个明显的情况是当您定义递归函数时,模式匹配使边缘条件更清晰,例如:
而不是:
这可能不是一个很好的例子,只需发挥您的想象力来找出更复杂的边缘条件即可! ;-)
就常规(比如 C)语言而言,我可以说你应该使用模式匹配而不是
switch
/case
和if
代替三元运算符。对于其他一切来说,这都是一个灰色地带,但模式匹配在 ML 语言家族中通常是首选。I don't think there's a clear cut answer to that question. First, the obvious case of pattern matching is when you need destructing, e.g.:
Another obvious case is when you're defining a recursive function, pattern matching make the edge condition clearer, e.g.:
instead of:
That might not be a great example, just use your imagination to figure out more complex edge conditions! ;-)
In term of regular (say C like) languages, I could say that you should use pattern matching instead of
switch
/case
andif
in place of the ternary operator. For everything else it's kind of a grey zone but pattern matching is usually preferred in the ML family of languages.据我所知,显着的区别是比赛语句中守卫的表达式是 模式 这意味着您可以执行一些操作来分解(破坏)匹配表达式的形状,正如 Nicolas 在他的回答中所示。这的另一个含义是这样的代码:
不会执行您期望的操作。这是因为 match 语句中的
x
并不引用其上面的 let 语句中的x
,而是模式的名称。在这种情况下,您需要使用if
语句。As far as I know the signifincant difference is that the expression at the guards in the match statement is a pattern which means you can do things that allow you to break apart the shape (destruct) the matched expression, as Nicolas showed in his answer. The other implication of this is that code like this:
won't do what you expect. This is because
x
in the match statement does not refer to thex
in the let statement above it but it's a name of the pattern. In cases like these you'd need to useif
statements.对我来说 if..then..else 相当于将 .. 与 | 匹配正确-> ..|假-> ..,但是如果您遇到嵌套模式匹配的情况,则有一个语法糖,以交错方式使用 if..else 可以帮助您避免使用 begin...end 来分隔不同级别的模式,
这比使用 if..else 更紧凑
For me if..then..else is equivalent to match .. with | true -> .. | false -> .., but there's a syntax sugar if you are facing cases with nested pattern matching, using if..else in an interlace way can help you avoiding to use begin...end to separate different level of patterns
is more compact than
模式匹配允许解构复合数据类型,并且通常能够在给定数据结构内匹配模式,而不是使用像 if..then 结构这样的条件。模式匹配还可用于使用 |x when (r == n) 类型构造的布尔相等情况。我还应该添加模式匹配比 if...then.. 构造更有效,所以请自由使用它!
Pattern matching allows for deconstruction of compound data types, and in general, the ability to match pattern within a given data structure, rather than using conditionals like the if.. then structure. Pattern matching can also be used for boolean equality cases using the |x when (r == n) type construct. I should also add pattern matching is a lot more efficient than if... then.. constructs, so use it liberally!