Now fixed, see
In this kind of context, last() is being evaluated by processing the sequence twice. But the mechanism that maintains the position variable isn't allowing for this.
Although, as I hinted, this is a design problem, it seems that the effect is fairly localised so I've been able to come up with a patch. It may prompt me to do a rethink on how last() is handled in XQuery. The current design is perhaps over-influenced by the fact that in XSLT it isn't in general possible to link a call on last() to the expression that it relates to, because last() may be called in a template invoked using xsl:apply-templates. In XQuery it's possible to do a lot more by means of static rewrites.
Michael Kay

From: [] On Behalf Of Rademacher, Gunther
Sent: 02 December 2007 21:43
Subject: [saxon] XQuery last() value of positional variable

A wrong result is returned when a numeric predicate based on function
last() is applied to a sequence that was built from values of a positional
variable, e.g.

        (for $x at $i in (1, 2) return $i)[last()]
returns 4, but should be 2. Seems like the result is always doubled.

Best regards,

Software AG – Sitz/Registered office: Uhlandstraße 12, 64297 Darmstadt, Germany, – Registergericht/Commercial register: Darmstadt HRB 1562 - Vorstand/ Management Board: Karl-Heinz Streibich (Vorsitzender/Chairman), David Broadbent, Mark Edwards, Dr. Peter Kürpick, David Mitchell, Arnd Zinnhardt; - Aufsichtsratsvorsitzender/ Chairman of the Supervisory Board: Frank F. Beelitz -