[xquery-talk] Global variables in XQuery
Massimo Franceschet
francesc at science.uva.nl
Thu Oct 5 12:43:41 PDT 2006
Thanks everybody for your prompt answers! The matter is much more clear
now. I have being using XQuery as a pure query language, and now I am
discovering it as a (functional) programming language. I apologise if my
question was 'frequently asked'.
On Wed, 2006-10-04 at 16:48 +0100, Michael Kay wrote:
> I'm not sure what your example is trying to do. It's quite hard to
> reverse-engineer a declarative algorithm from a procedural one, especially
> an incorrect procedural one. It's usually easier to start again from the
> statement of requirements.
In fact my example was just a dummy example without an intended meaning.
I was just meant to fix the ideas. Nevertheless, there are many
occasions in which a programmer needs to both read and write a global
variable, especially when recursive functions are involved. For
instance, suppose I want to know the number of recursive calls of my
recursive function (this number is an lower bound of the space
complexity of the function). Suppose my recursive function is the
following that computes the factorial of a number (of course it's pretty
obvious what is the recursion depth in this case, but you can imagine
more complicated examples in which this is not so clear):
declare namespace my = 'my:stuff';
declare variable $my:depth as xs:integer := 0;
declare function my:factorial($n as xs:integer) as xs:integer {
let $my:depth := $my:depth + 1
return
if ($n < 2)
then 1
else $n * my:factorial($n - 1)
};
In a pure procedural environment, after an invocation of the function
factorial, the global variable my:depth contains the depth of the
recursion, which might be used by the caller. In XQuery, this is not the
case, since, global variables cannot be modified inside a function. Of
course, we can use an extra parameter of factorial for the depth, and
this does the job in XQuery. However, the same mathematician that would
rate the assignment X = X + 1 as odd or false would also be confused by
a factorial function with *two* arguments.
Cheers,
Massimo
More information about the talk
mailing list