[xquery-talk] a conceptual clarification

Per Bothner per at bothner.com
Wed Mar 2 22:27:07 PST 2005


Ronald Bourret wrote:
> The following is from query 2:
> 
>   declare function my:square ($x)
>   {
>     let $x := $x * $x
>     return $x
>   };
> 
> Just to be clear, this is legal because the $x in the parameter 
> declaration is in a different namespace / symbol space / whatever you 
> call it that the $x in the let statement?

No - they're in the same name space.

> But even if this is true, how 
> does one decide which $x is returned by the return statement?

This is "lexical scoping", as in many programming languages.
The compiler "chooses" the *textually* "closest" definition.
This is explained in any undergraduate "comparative programming
languages" class or textbook.

> Based on this, are the following functions legal or illegal?
> 
>    declare function foo()
>    {
>       let $x := 1
>       let $x := 2
>       return $x
>    }
> 
>    declare function bar()
>    {
>       let $x := 2
>       let $x := $x * $x
>       return $x
>    }

Both are legal.  (Though I think allowing them is a Bad Idea.)

In both cases the second "inner $x *hides* the first "outer" $x.
But for the $x * $x "sees" the "outer $x.  Hence the result is 4.
-- 
	--Per Bothner
per at bothner.com   http://per.bothner.com/


More information about the talk mailing list