For expressions and the position() function

Hi,

Following on from David C.'s post about the identity of the context
item within the for expression, I'd like to make another observation -
it's very difficult to perform different operations on items within a
sequence based on their position in the sequence.

Take the example of manipulating coordinates to add 50 to odd
coordinates. With the simple mapping operator that I suggested
yesterday, this can be done with:

  $coordinates -> if (position() mod 2) then . + 50 else .

With a for expression, on the other hand, you cannot use the
position() function (because it gives the context position from the
outer focus), and therefore have to create something like:

  for $i in (1 to count($coordinates))
  return if ($i mod 2)
         then $coordinates[$i] + 50
         else $coordinates[$i]

[Here assuming that the fact you can't use predicates on sequences
that aren't node sequences is a bug in the XPath 2.0 WD.]
         
I think this is likely to be quite inefficient, because the number of
items in the sequence have to be counted up front, and the sequence is
indexed into each time, leading to multiple traversals of the same
sequence. Compare to:

  for $c in $coordinates
  return if (position() mod 2) then . + 50 else .

where the $coordinates sequence is only traversed once, and the
$coordinates sequence itself could be constructed lazily.

Cheers,

Jeni
---
Jeni Tennison
http://www.jenitennison.com/

Received on Saturday, 5 January 2002 07:49:19 UTC