什么时候喜欢`````````````` [英] When to prefer `and` over `andalso` in guard tests

查看:120
本文介绍了什么时候喜欢``````````````的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇为什么逗号<,>是防护测试中而不是 andalso 的快捷方式。



由于我称自己为C本地人,我没有看到短路布尔评估的任何缺点。



我使用 to_core 标记编译了一些测试代码,以查看实际生成的代码。使用逗号,我看到左边的值,右边的和值被评估,两者和。使用 andalso ,您可以在案例块中有一个案例块,不调用 erlang:和/ 2



我没有进行基准测试,但我不敢相信 andalso 变体是更快的。

解决方案

深入了解:




  • 只有分离的测试,从左到右进行评估,直到没有更多,并且防守成功或测试失败,整个卫兵失败了。后来; 被添加到允许在同一子句中的备用警卫。如果守卫在测试之前评估的双方,那么有人在路上错了。 @ Kay的例子似乎意味着他们应该从左到右。


  • 布尔运算符只能在后卫的后卫中使用。 p>


  • 连同 xor 不是,是一个布尔运算符,不适用于控制。他们都是严格,并首先评估他们的参数,如算术运算符 + - * 和'/'。在C中也存在严格的布尔运算符。


  • 短路控制运算符 andalso orelse 稍后添加以简化一些代码。如您所说,编译器将它们扩展为嵌套的 case 表达式,因此在使用它们方面没有任何性能提升,只是方便和清晰的代码。这将解释您看到的结果代码。


  • NB 在守卫中有测试而不是表达式。有一个微妙的区别,这意味着在使用 andalso 相当于时, / code>使用 orelse 不等同于; 。这是另一个问题。提示:这一切都是关于失败的。




所以 andalso 有他们的位置。


I am curious why the comma ‹,› is a shortcut for and and not andalso in guard tests.

Since I'd call myself a "C native" I fail to see any shortcomings of short-circuit boolean evaluation.

I compiled some test code using the to_core flag to see what code is actually generated. Using the comma, I see the left hand value and right and value get evaluated and both and'ed. With andalso you have a case block within the case block and no call to erlang:and/2.

I did no benchmark tests but I daresay the andalso variant is the faster one.

解决方案

To delve into the past:

  • Originally in guards there were only , separated tests which were evaluated from left-to-right until either there were no more and the guard succeeded or a test failed and the guard as a whole failed. Later ; was added to allow alternate guards in the same clause. If guards evaluate both sides of a , before testing then someone has gotten it wrong along the way. @Kay's example seems to imply that they do go from left-to-right as they should.

  • Boolean operators were only allowed much later in guards.

  • and, together with or, xor and not, is a boolean operator and was not intended for control. They are all strict and evaluate their arguments first, like the arithmetic operators +, -, * and '/'. There exist strict boolean operators in C as well.

  • The short-circuiting control operators andalso and orelse were added later to simplify some code. As you have said the compiler does expand them to nested case expressions so there is no performance gain in using them, just convenience and clarity of code. This would explain the resultant code you saw.

  • N.B. in guards there are tests and not expressions. There is a subtle difference which means that while using and and andalso is equivalent to , using orelse is not equivalent to ;. This is left to another question. Hint: it's all about failure.

So both and and andalso have their place.

这篇关于什么时候喜欢``````````````的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆