Pete
Pete

Reputation: 17132

XQuery function: variable and expression vs FLOWR

Method 1

declare function foo($bar){
     variable $x := some_fn($bar/yada/yada);
     variable $y := other_fn($x);
     $y
};

Method 2 (FLOWR)

declare function foo($bar){
     let $x := some_fn($bar/yada/yada)
     let $y := other_fn($x)
     return $y
};

Different syntax, same result; from the processor's point of view, what's different? What reasons are there to prefer one method over the other? For readability, I prefer the FLOWR.

Upvotes: 2

Views: 161

Answers (2)

Francis Avila
Francis Avila

Reputation: 31621

The first method (using variable) relies on non-standard extensions. At least on Zorba, this is called the Zorba Scripting Extension (scroll to the bottom, header "Scripting") which adds side-effecting imperative programming constructs to XQuery. This extension is on in Zorba by default but can be turned off.

I cannot find a specification for this extension. To add to the confusion, there is a W3C XQuery extension called the XQuery Scripting Extension which adds the same feature but with a different syntax and Zorba does not implement this W3C extension. The W3C syntax is declare $x ...; (instead of variable $x ...; at the top of a block.

Anyway, here are the differences between your two code snippets:

  1. Your variable method is non-standard and possibly Zorba-specific; your FLWOR is vanilla XQuery 1.0.
  2. The variable method is side-effecting: $x and $y are in-scope in the entire block and can be re-assigned at any moment. With the FLWOR method, each let binding is only visible to the following FLWOR clauses.
  3. I don't know if there are any performance implications for such a simple example. Speaking very generally, sometimes mutability and side-effects are faster, but such code is usually harder for compilers to optimize (and they might be able to optimize immutable pure code better than hand-written mutable code). But this completely depends on what Zorba does under the hood.

I would not use variable because it is non-standard and because I prefer the predictability of expression-based, non-imperative code. Making XQuery imperative sounds like a misfeature to me.

Upvotes: 4

joemfb
joemfb

Reputation: 3056

As @wst commented, your first example isn't valid XQuery. The variable keyword is only valid in a variable declaration, which must be in the query prolog:

declare variable $a := "a";

I don't have Saxon handy, but I tested something similar to your example in MarkLogic, Zorba, and eXistDB, and each threw syntax errors.

Upvotes: 0

Related Questions