我有一个长度为 $n 的序列初始化为零:
let $seq := (for $i in (1 to $n) return 0)
我可以轻松获得职位...
return $seq[5]
...但是我该如何更新呢?(以下不起作用)
let $seq[5] := $seq[5] + 1
我有一个长度为 $n 的序列初始化为零:
let $seq := (for $i in (1 to $n) return 0)
我可以轻松获得职位...
return $seq[5]
...但是我该如何更新呢?(以下不起作用)
let $seq[5] := $seq[5] + 1
如果您正在使用支持 XQuery 3 映射的 XQuery 实现(例如 Saxon、BaseX),您可以使用这些:
declare namespace map="http://www.w3.org/2005/xpath-functions/map";
(: Fill map with square numbers :)
let $map := map:new(
for $i in (1 to 10)
return map:entry($i, $i*$i)
)
(: Overwrite a single value :)
let $map := map:new(($map, map:entry(2, 5)))
(: Fetch this value :)
return map:get($map, 2)
But generally it is possible to solve a problem without maps and in most cases this code will probably run faster as it will get better optimized.
XQuery 是一种函数式语言,而不是过程式语言,因此变量是不可变的——它们一旦分配就不能更新。你需要做这样的事情并创建一个新序列:
let $seq2 :=
for $n at $pos in $seq
if ($pos eq 5)
then $n + 1
else $n
通常,在 XQuery 中,最好设计算法以便不需要这种类型的可变变量解决方法。如果您有需要更新的数据,请考虑将其放入数据库中。
...but how do I update it? (the following doesn't work)
let $seq[5] := $seq[5] + 1
Using pure XPath (which is also pure XQuery :) here is probably the shortest way to specify this:
subsequence($seq, 1, 4), $seq[5] + 1, subsequence($seq, 6)
This produces a new sequence whose items are the same as the items of $seq
, except that its 5th item's value is $seq[5] + 1
.
As others have noted, XPath and XQuery are functional languages and among other things this means that a variable, once defined, cannot have its value modified.