警卫表情什么时候合适?
这是我编写的一个使用 if-else
分支和保护表达式的示例。什么时候一个比另一个更合适?我想知道这一点的主要原因是因为语言通常有一种惯用的做事方式。
test1 a b =
if mod b 3 ≡ 0 then a + b
else if mod b 5 ≡ 0 then a + b
else a
test2 a b
| mod b 3 ≡ 0 = a + b
| mod b 5 ≡ 0 = a + b
| otherwise = a
Here is an example I wrote that uses if-else
branches and guard expressions. When is one more appropriate over the other? The main reason I want to know this is because languages typically have a idiomatic way of doing things.
test1 a b =
if mod b 3 ≡ 0 then a + b
else if mod b 5 ≡ 0 then a + b
else a
test2 a b
| mod b 3 ≡ 0 = a + b
| mod b 5 ≡ 0 = a + b
| otherwise = a
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你给出的例子很好地展示了警卫如何更好。
有了这些守卫,你就得到了一个非常简单易读的条件和结果列表——非常接近数学家编写函数的方式。
另一方面,使用
if
时,您会得到一个有点复杂(基本上是 O(n2) 阅读难度)的嵌套表达式结构,其中关键字以不规则的间隔插入。对于简单的情况,它基本上是在
if
和保护之间进行折腾 -if
在一些非常简单的情况下甚至可能更具可读性,因为它更容易写在一行上。然而,对于更复杂的逻辑,守卫是表达相同想法的更好方式。The example you give is a very good demonstration of how guards are better.
With the guards, you have a very simple and readable list of conditions and results — very close to how the function would be written by a mathematician.
With
if
, on the other hand, you have a somewhat complicated (essentially O(n2) reading difficulty) structure of nested expressions with keywords thrown in at irregular intervals.For simple cases, it's basically a toss-up between
if
and guards —if
might even be more readable in some very simple cases because it's easier to write on a single line. For more complicated logic, though, guards are a much better way of expressing the same idea.我一直认为这是一个偏好问题。就我个人而言,我更喜欢第二个,我认为 if-else 比守卫给人一种更命令式的感觉,而且我发现守卫更容易阅读。
I always thought it was a matter of preference. Personally, I prefer the second one, I think that the if-elses give a more imperative feel than the guards, and I find the guards easier to read.