XQuery

Priscilla Walmsley (pwalmsley@datypic.com)

ISBN: 0596006349

1st edition, 2007, O'Reilly Media, Inc.

# Chapter 8: Functions

Example 8-1. A function declaration
```declare function local:discountPrice(
\$price as xs:decimal?,
\$discount as xs:decimal?,
\$maxDiscountPct as xs:integer?) as xs:decimal?
{
let \$maxDiscount := (\$price * \$maxDiscountPct) div 100
let \$actualDiscount := min((\$maxDiscount, \$discount))
return (\$price - \$actualDiscount)
};
(:line below inserted to give \$prod a value :)
let \$prod := doc("prices.xml")//prod[1] return
local:discountPrice(\$prod/price, \$prod/discount, 15)```
Example 8-2. Handling the empty sequence
```declare function local:discountPrice(
\$price as xs:decimal?,
\$discount as xs:decimal?,
\$maxDiscountPct as xs:integer?) as xs:double?
{
let \$newDiscount    := if (\$discount) then \$discount else 0
let \$maxDiscount    := if (\$maxDiscountPct)
then (\$price * \$maxDiscountPct) div 100
else 0
let \$actualDiscount := min((\$maxDiscount, \$discount))
return (\$price - \$actualDiscount)
};
(:line below inserted to give \$prod a value :)
let \$prod := doc("prices.xml")//prod[1] return
local:discountPrice(\$prod/price, \$prod/discount, 15)```
Example 8-3. Invalid use of context in a function body
```declare function local:prod2ndDigit() as xs:string? {
substring(number, 2, 1)
};
doc("catalog.xml")//product[local:prod2ndDigit() > '5']```
Example 8-4. Passing the context item to the function
```declare function local:prod2ndDigit(\$prod as element()?) as xs:string? {
substring(\$prod/number, 2, 1)
};
doc("catalog.xml")//product[local:prod2ndDigit(.) > '5']```
Example 8-5. A recursive function
```declare namespace functx = "http://www.functx.com";
declare function functx:num-descendant-elements
(\$el as element()) as xs:integer {
sum(for \$child in \$el/*
return functx:num-descendant-elements(\$child) + 1)
};```