Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an if statement without an else in XQuery?

I wish to create an if statement without an else portion in XQuery.

For example:

<results>
   { 
   if (5 = 5) then
       <foo/>
   }
<results>

How do I do this?

I also tried this:

<results>
   { 
   if (5 = 5) then
       <foo/>
   else
       return
   }
<results>

which although compiles, doesn't work when running!

like image 874
Yahya Uddin Avatar asked Dec 24 '22 11:12

Yahya Uddin


2 Answers

There are no if statements in XQuery without else. Return the empty sequence instead (), or any reasonable identity element (which is usually what you will require if nothing specific is defined).

if ($foo eq "bar")
then
  42
else
  ()

In contrast to procedural languages, where "no else statement" simply means "do nothing" XQuery is a functional language, which also implies that every operation must have "something" returned. How to proceed "nothing"? It might have been possible to declare "no else statement means returning the empty sequence instead", but the W3C XML Query working group seems to have decided requiring to explicitely define returning nothing instead. All in all, this results in easier to understand and possibly better code, as you have to think about what the "else" value to return is; as there could be a lot of reasonable values: 0 if you're adding up something, 1 if multiplying, the empty string "" for joining strings without separators, the empty sequence if joining strings with separators, ...

Do not use "empty return statements"

Using an "empty" return is not possible, but returns <return/> children elements in the current context instead, so else return is merely a else ./return. This will not only fail (and return something) if the current context indeed has <return/> children, but also if no context at all is bound.

Do not return empty strings

Returning an empty string does not return nothing, but the empty string, which is a value and might even break typing at another place. Returning the empty string is no general solution, but might be in some specific cases.

like image 174
Jens Erat Avatar answered Jan 01 '23 11:01

Jens Erat


You could use a filter expression instead:

<results>
   { 
       <foo/> [5 = 5]
   }
</results>
like image 35
BeniBela Avatar answered Jan 01 '23 09:01

BeniBela