I am looking for an example which shows that XQuery expression evaluation is not sequential. It is always mentioned when comparing the functional nature of XQuery with procedural languages.
E.g. in XQuery, 2nd edition, in the section below:
The FLWOR expression with its for clause is similar to loops in procedural languages such as C. However, one key difference is that in XQuery, because it is a functional language, the iterations are considered to be in no particular order. They do not necessarily occur sequentially, one after the other.
In general, the language is designed so that you can't tell what the order of evaluation is, which makes it difficult to demonstrate that it's not what you expect. To observe the actual order of evaluation, you need to do something that has side-effects, which generally means straying outside the language specification and using vendor extensions. For example you could use the EXPath file module and issue calls to file:append-text()
, and then examine the order of entries added to the external text file.
Of course, it wouldn't prove anything if the entries in the file are in exactly the order you expect. Query processors aren't going to use a non-obvious order of execution just for the fun of it. They will only do so if there is something to be gained by changing the order. Saxon, for example, will delay evaluating variables until they are used, and will lift expressions out of a loop if it can. But you then have the problem, that if you use functions with side-effects like file:append-text()
to observe this behaviour, Saxon might detect that your code has side-effects and suppress the optimization.