Datypic Logo
XQuery

XQuery

Priscilla Walmsley (pwalmsley@datypic.com)

ISBN: 1491915102

2nd edition, 2015, O'Reilly Media, Inc.

Chapter 23: Function Items and Higher-Order Functions

Please note that the book contains many inline examples and informal tables that are not provided here.

Example 23-1. Simple higher order function
xquery version "3.0";
declare function local:for-each
   ($seq, 
    $f) 
   {
    for $item in $seq return $f($item)
   };
local:for-each( ("abc", "def"), upper-case#1)
Example 23-2. Simple higher order function with sequence types
xquery version "3.0";
declare function local:for-each
   ($seq as item()*, 
    $f as function(item()) as item()*) 
   as item()* 
   {
    for $item in $seq return $f($item)
   };
local:for-each( ("abc", "def"), upper-case#1)
Example 23-3. Price list generation without higher-order functions
declare function local:price-list
   ($price-doc as document-node()) {
    <html>
      <head>
        <title>Price List</title>
        <link href="companystandard.css"/>
      </head>
      <body>
        <h1>Price List</h1>
        <table>
          <tr>
            <th>Prod number</th>
            <th>Price</th>
          </tr>
          {for $prod in $price-doc//priceList[@effDate < current-date()]/prod
          return
          <tr>
            <td>{data($prod/@num)}</td>
            <td>{if (exists($prod/discount))
                 then $prod/price - $prod/discount
                 else data($prod/price)}</td>
            </tr>
        }</table>
      </body>
    </html>
};
Example 23-4. Price list generation with function for discount algorithm
xquery version "3.0";
declare function local:price-list
   ($price-doc as document-node(),
    $price-calc-func as function(element(prod)) as xs:decimal) {
    <html>
      <head>
        <title>Price List</title>
        <link href="companystandard.css"/>
      </head>
      <body>
        <h1>Price List</h1>
        <table>
          <tr>
            <th>Prod number</th>
            <th>Price</th>
          </tr>
          {for $prod in $price-doc//priceList[@effDate < current-date()]/prod
          return
          <tr>
            <td>{data($prod/@num)}</td>
            <td>{$price-calc-func($prod)}</td>
          </tr>
        }</table>
      </body>
    </html>
};
declare function local:price-based-on-discount
  ($prod as element(prod)) as xs:decimal {
   if (exists($prod/discount))
   then xs:decimal($prod/price) - xs:decimal($prod/discount)
   else xs:decimal($prod/price)
};
declare function local:price-based-on-percent
 ($prod as element(prod)) as xs:decimal {
   xs:decimal($prod/price) * .90
};
Datypic XQuery Services