Conditionals

A conditional expression consists of a condition and two branch expressions. The condition must be a Boolean. If both branches have the same type, then the type of the conditional expression is also that type. Assume that $x and $y are both integers. Here is an example:

 if ($x<$y) then 3 else 4  has type  xs:integer 

If the two branches have different types, then the type of the conditional expression is the union of those types. Here is an example:

 if ($x<$y) then "three" else 4.00  has type  (xs:string  xs:decimal) 

Recall that in the XQuery formal type notation, a vertical bar indicates the union of two types. The union of a type with itself is just the type, so the rule about conditionals with two branches of the same type is just a special case of the rule for two branches with different types.

Unlike arithmetic operators, conditionals involve no notion of promotion. Here is an example:

 if ($x < $y) then 4.2e1 else 69  has type  (xs:double  xs:integer) 

At run-time, if the else branch is taken, then we do not expect the integer 69 to be promoted to a double, and so the type system also does not perform any promotion.

When arithmetic is performed on an operand expression with a union type, promotion is applied to each member of the union separately. Here is an example:

 (if ($x < $y) then 4.2e1 else 69) + 0.5  has type  (xs:double  xs:decimal) 

For the then branch, the promotion rule specifies that adding an xs:double and an xs:decimal yields an xs:double , and for the else branch, the promotion rule specifies that adding an xs:integer and an xs:decimal yields an xs:decimal , thus the type of the result is (xs:double xs:decimal) .

Early in this chapter, we explained that static type analysis is conservative: The type assigned to an expression always contains all possible values of the expression, but often it will contain more values than the expression can yield. We have already seen one example of this, where 42 is assigned the type xs:integer rather than the type xs:positiveInteger . Here is another example. Say that $x , $y , $z , and $n are four integer variables , and say that the function fermat($x,$y,$z,$n) returns true if $n is greater than 2 and $x $n + $y $n = $z $n . Now consider this conditional expression:

 (if (fermat($x,$y,$z,$n) then 1 else "two") + 3 

This raises a static type error. After 350 years of uncertainty, mathematicians now know that the else branch of the conditional expression above can never be executed. But we don't expect a query analyzer to be clever enough to know that. So the typing rules presume that either branch of a conditional may be executed, and this is a good enough compromise for practical purposes.



XQuery from the Experts(c) A Guide to the W3C XML Query Language
Beginning ASP.NET Databases Using VB.NET
ISBN: N/A
EAN: 2147483647
Year: 2005
Pages: 102

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net