2016-12-21 7 views
3

私は$ book、$ title、$ authorがFLWORのスコープ内にあることを理解していますが、なぜ$ titleと$ authorがシーケンス内で動作し、$ bookがそうでないのか分かりません。

(: 
    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 :) 

答えて

4

FLWORのFORでバインドされた変数は、FLWOR内でのみ表示されます。

XQueryは手続き型言語ではありません。それは機能的です。実行システムがあなたの表現を並行して、または順不同で実行することは、まったく問題ありません。これは関数型言語の優れた機能の1つです。

画像a数学関数(a*b) + (c*d)。評価システムは、a*bc*dの部分を並列に実行し、ユーザーはそれを知ることができません。それはXQueryの考え方と同じです。並行して多くの作業を行うことができ、管理する必要はなく、わからないこともあります。

あなたの例では、3つの式がステートメントで提供されており、それぞれ独立しています。あなたのプログラムは、上から下へ排他的に走っていると考えるべきではありません。

ポップクイズ:これは何を返すのですか?

for $i in (1 to 3) 
return $i, 4 

それは4を返す式が続く1 2 3を返すFLWOR式だからそれは1 2 3 4です。そして、2番目の式で$iを参照することはできません。

for $i in (1 to 3) 
return $i 
, 
4 
+1

つまり、余分な括弧を使用して機能させる必要があります。例:返信用(

{($タイトル、 "by"、$ author)}、...、$ book) ' – grtjn

関連する問題