I understand that $book, $title and $author are scoped within FLWOR, but I don't understand why $title and $author works in the sequence and $book does not.
(:
A note on variable scope.
Variables in a FLWOR expression are scoped only to the FLWOR expression.
Local variables declared in the prolog are scoped to the main module.
:)
(: start of prolog :)
xquery version "1.0-ml";
declare namespace bks = "http://www.marklogic.com/bookstore";
declare variable $scope-example := "2005";
(: end of prolog :)
(: start of query body :)
(
"remember an XQuery module returns a sequence -- this text is the first item, and then the results of the FLWOR",
for $book in /bks:bookstore/bks:book
let $title := $book/bks:title/string()
let $author := $book/bks:author/string()
let $year := $book/bks:year/string()
let $price := xs:double($book/bks:price/string())
where $year = $scope-example (: we can do this because my local variable is scoped to the module :)
order by $price descending
return
<summary>{($title, "by", $author)}</summary>
,
"and now another item, but I cant reference a variable from the FLWOR expression outside of the FLWOR, it will fail like this",
$book
)
(: end of query body :)
A variable bound in the FOR of a FLWOR is only visible within the FLWOR.
XQuery is not a procedural language; it's functional. It's perfectly fine for an executing system to run your expressions in parallel or out of order. That's one of the cool features of a functional language.
Picture a math function (a*b) + (c*d). An evaluating system might do the a*b and c*d parts in parallel without the user being able to tell. That's the same idea in XQuery. Lots of work can be happening in parallel and you don't have to manage it and you don't even know.
In your example, you're providing 3 expressions in your statement, and each is independent. You shouldn't think of your program as running exclusively top to bottom leaving side effect variable changes in its wake.
Pop quiz: What does this return?
for $i in (1 to 3)
return $i, 4
It's 1 2 3 4 because it's a FLWOR expression returning 1 2 3 followed by an expression returning 4. And you can't reference $i in the second expression.
for $i in (1 to 3)
return $i
,
4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With