三元运算符和惰性求值
Ternary Operator and lazy evaluation
三元运算符是惰性求值的一个例子吗?
如果我们假设代码片段如下:
变量=条件?函数 1(参数):函数 2(参数);
能不能算个惰性求值的例子?
在大多数语言中 - 是的,它是延迟计算的。然而情况并不一定如此。来自 Wikipedia:
Note that some languages may evaluate 'both' the true- and
false-expressions, even though only one or the other will be assigned
to the variable. This means that if the true- or false-expression
contain a function call, that function may be called and executed
(causing any related side-effects due to the function's execution),
regardless of whether or not its result will be used.
例如,在 Delphi 中,它不是惰性求值的:
Unlike a true ternary operator however, both of the results are
evaluated prior to performing the comparison. For example, if one of
the results is a call to a function which inserts a row into a
database table, that function will be called whether or not the
condition to return that specific result is met.
三元运算符是惰性求值的一个例子吗? 如果我们假设代码片段如下: 变量=条件?函数 1(参数):函数 2(参数); 能不能算个惰性求值的例子?
在大多数语言中 - 是的,它是延迟计算的。然而情况并不一定如此。来自 Wikipedia:
Note that some languages may evaluate 'both' the true- and false-expressions, even though only one or the other will be assigned to the variable. This means that if the true- or false-expression contain a function call, that function may be called and executed (causing any related side-effects due to the function's execution), regardless of whether or not its result will be used.
例如,在 Delphi 中,它不是惰性求值的:
Unlike a true ternary operator however, both of the results are evaluated prior to performing the comparison. For example, if one of the results is a call to a function which inserts a row into a database table, that function will be called whether or not the condition to return that specific result is met.