Thanks for the feedback. Some initial thoughts:

>I tested 5 different algorithms:

>A1: Using the simple mapping operator: $seq[($seq!(if(. gt $threshold) then position() else ()))[1] - 1]

>This is very dependent on an optimization rule that says "if the predicate is a numeric value whose value doesn't depend on the position in the sequence, then evaluate the predicate once, outside the loop". This optimization basically changes this from a quadratic algorithm if evaluated naively, to a linear one. It might be that this predicate is somehow failing to pass this test, and is therefore being evaluated repeatedly once for each item in $seq. You can always do the same optimization by hand by writing for $i in ($seq!(if(. gt $threshold) then position() else ()))[1] - 1 return $seq[$i].

>A2: Straight predicate:  $seq[. lt $threshold][last()]  <--does not make full use of sorted nature of sequence

>A3: Recursive XSL-Function option (create an XSL-function that executes the suggestion made by Michael Kay at

>I tried to test an Xpath-inline-recursion version, but kept getting an error saying that the variable was not declared.}

Recursive anonymous inline functions can be done in theory using a technique called Y-combinators, but I find it mind-blowing and someone else will have to explain it!

>A4: Call a function using the <xsl:iterate> command to scan the list, using <break/> to stop processing once the threshold is met.

>A5: Same as A4, but without the use of a dedicated function.

The interaction of bytecode generation with tail-recursion is something we were aware of, but it's something we really need to address. I think self-recursion works OK with bytecode, but not tail-calls on a different function. Unfortunately the design of Java bytecode simply doesn't allow one to jump from the end of one routine to the start of another, without incrementing the stack, so we need to find some other way of achieving the same effect.