In this post, I explore short-circuit boolean evaluation in XPath.
Let’s start with this reference task:
Let $seq be a possibly empty sequence of integer. The task is to compute a boolean which is true if the first item is the maximum integer and false otherwise. For this purpose, deem the case of an empty sequence NOT have the property that the first item is the maximum. Now there many possible solutions to this task, but for argument’s sake, let’s restrict our solutions to the form of …
index-of( $seq, max( $seq))[1] eq 1
… or something derived from this.
The problem with the using above as in in XPath 2.0 occurs with an edge case. If $seq is empty, this will return an error. So what we really want is this imaginary XPath 2.0 expression..
exists( $seq) short-circuit-and index-of( $seq, max( $seq))[1] eq 1
where ‘short-circuit-and’ is an imaginary XPath 2.0 operator which does short-circuit boolean evaluation from left to right. When XPath 1.0 compatibility mode is set to true, we can use the ‘and’ operator for this purpose. Sadly we cannot safely do so when the comp ability mode is set to false. In the default case of compatibility mode equals false, the above expression returns an implementation dependent result. For the edge case, some processors may return false and other processors may return error. In other words, XPath 2.0 does not implement short-circuit boolean evaluation.
Here is how we can achieve the effect of short-circuit boolean evaluation in XPath 2.0
if (exists( $seq)) then index-of( $seq, max( $seq))[1] eq 1 else false()
Here are the implementation patterns for short-circuit boolean evaluation in XPath 2.0 (and probably the future XPath 3.0).
Short-circuit AND
expression-a short-circuit-and expression-b ==> if (expression-a) then (expression-b) or false()
Short-circuit OR
expression-a short-circuit-or expression-b ==> if (expression-a) then true() else expression-b
thanks for sharing this information is really helpful