你正在從一個迫切需要的角度來解決這個問題。
在XQuery中,您可以設置變量的值,但您永遠無法更改它們。
做迭代式算法的正確方法是用遞歸函數:
declare funciton local:most($sequence, $index, $value, $count)
{
let $current=$sequence[$index]
return
if (empty($current))
then $value
else
let $current-count = count(index-of($current, $sequence))
return
if ($current-count > $count)
then local:most($sequence, $index+1, $current, $current-count)
else local:most($sequence, $index+1, $value, $count)
}
但接近問題的一個更好的方法是通過描述一個非迭代的方式的問題。在這種情況下,序列中的所有不同值都需要顯示任何不同值的最大次數的值。
以前森泰斯翻譯成XQuery是
let $max-count := max(for $value1 in distinct-values($sequence)
return count(index-of($sequence, $value1)))
for $value2 in distinct-values($sequence)
where (count(index-of($sequence, $value2)) = $max-count
return $value2
再好問題(+1)。答案是一個XPath單行表達式......將盡量縮短它。 – 2010-06-24 19:17:12