有短路乘法吗? [英] Is there such a thing as short circuit multiplication?
问题描述
我们都知道逻辑表达式中的短路,即何时
We all know about short circuiting in logical expressions, i.e. when
if ( False AND myFunc(a) ) then
...
不必费心执行myFunc()
,因为if
条件不可能成立.
doesn't bother executing myFunc()
because there's no way the if
condition can be true.
我很好奇您的日常代数方程式是否相等
I was curious as to whether there is an equivalent for your everyday algebraic equation, say
result = C*x/y + z
如果C=0
,则没有必要评估第一个项.如果x
和y
是标量,则在性能上并没有多大关系,但是如果我们假装它们是大型矩阵,并且运算成本很高(并且适用于矩阵),那么肯定会有所作为.当然,您可以通过抛出if C!=0
语句来避免这种极端情况.
If C=0
there is no point in evaluating the first term. It wouldn't matter much performance-wise if x
and y
were scalars, but if we pretend they are large matrices and the operations are costly (and applicable to matrices) then surely it would make a difference. Of course you could avoid such an extreme case by throwing in an if C!=0
statement.
所以我的问题是这样的功能是否存在以及是否有用.我不是一个程序员,所以可能是以我没遇到过的名字来做的.如果是这样,请赐教:)
So my question is whether such a feature exists and if it is useful. I'm not much of a programmer so it probably does under some name that I haven't come across; if so please enlighten me :)
推荐答案
您所讨论的概念有不同的名称:惰性评估,非严格评估, 按需呼叫,仅举几例,实际上比避免在这里和那里乘法的功能要强大得多.
The concept you are talking about goes under different names: lazy evaluation, non-strict evaluation, call by need, to name a few and is actually much more powerful than just avoiding a multiplication here and there.
有些编程语言例如 Haskell 或弗雷格(Frege)的评估模型是非严格的.编写短路"乘法运算符非常容易,例如,您可以编写以下内容:
There are programming languages like Haskell or Frege whose evaluation model is non-strict. There it would be quite easy to write your "short circuiting" multiplication operator, for example you could write something like:
infixl 7 `*?` -- tell compiler that ?* is a left associative infix operator
-- with precedence 7 (like the normal *)
0 *? x = 0 -- do not evaluate x
y *? x = y * x -- fall back to standard multiplication
这篇关于有短路乘法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!