This [[Module Library|XQuery Module]] adds some useful higher-order functions, additional to the [[Higher-Order Functions]] provided by the official specification.
With {{Announce|Version 11}}, many functions have been removed in favor of new features of XQuery 4:
{|
|- valign="top"
| '''BaseX 10'''
| '''XQuery 4'''
|- valign="top"
| {{Code|hof:drop-while}}
| [https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-drop-while <code>fn:items-starting-where</code>]
|- valign="top"
| {{Code|hof:id}}
| [https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-identity <code>fn:identity</code>]
|- valign="top"
| {{Code|hof:until}}
| [https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-iterate-while <code>fn:iterate-while</code>]
|- valign="top"
| {{Code|hof:take-while}}
| [https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-take-while <code>fn:items-before</code>]
|}
=Conventions=
| '''Summary'''
|This function is similar to [[Higher-Order Functions#fn:fold-left|fn:fold-left]], but it returns a list of successive reduced values from the left. It is equivalent to:
<syntaxhighlight pre lang="'xquery"'>
declare function hof:scan-left($input, $acc, $action) {
if(empty($input)) then $acc else (
)
};
</syntaxhighlightpre>
|- valign="top"
| '''Examples'''
|
* Returns triangular numbers:
<syntaxhighlight pre lang="'xquery"'>
hof:scan-left(1 to 10, 0, function($a, $b) { $a + $b })
</syntaxhighlightpre>
|}
| '''Summary'''
|Returns the {{Code|$k}} items in {{Code|$input}} that are greatest when sorted by the result of {{Code|$key}} applied to the item. The function is a much more efficient implementation of the following scheme:
<syntaxhighlight pre lang="'xquery"'>
(for $item in $input
order by $key($item) descending
return $item
)[position() <= $k]
</syntaxhighlightpre>
|- valign="top"
| '''Examples'''
* {{Code|hof:const(42, 1337)}} returns {{Code|42}}.
* With higher-order functions:
<syntaxhighlight pre lang="'xquery"'>
let $zip-sum := function($f, $seq1, $seq2) {
sum(for-each-pair($seq1, $seq2, $f))
$sum-left((1, 1, 1, 1, 1), 1 to 5)
)
</syntaxhighlightpre>
* Another use-case: When inserting a key into a map, {{Code|$f}} decides how to combine the new value with a possibly existing old one. {{Code|hof:const}} here means ignoring the old value, so that's normal insertion.
<syntaxhighlight pre lang="'xquery"'>
let $insert-with := function($f, $map, $k, $v) {
let $old := $map($k)
$ins($map, 'foo', 42)('foo')
)
</syntaxhighlightpre>
returns {{Code|3 42}}
|}