Main Page » XQuery » Functions » Higher-Order Functions

Higher-Order Functions

This module adds some useful higher-order functions, in addition to the standard Higher-Order Functions.

The following functions have been incorporated into the official specification:

BaseX 10 XQuery 4
hof:drop-while fn:subsequence-where
hof:id, hof:const fn:identity
hof:until fn:while-do, fn:do-until
hof:take-while fn:take-while

Conventions

All functions are in the http://basex.org/modules/hof namespace, to which the hof prefix is statically bound.

Loops

hof:fold-left1

Signature
hof:fold-left1(  $input   as item()+,  $action  as fn(item()*, item()) as item()*) as item()*
SummaryWorks the same as fn:fold-left, but does not need a seed, because the sequence must be non-empty.
Examples
hof:fold-left1(1 to 10, op('+'))
Result: 55
hof:fold-left1((), fn($a, $b) { $a + $b })
Raises XPTY0004, because $input has to be non-empty.

Sorting

hof:top-k-by

Signature
hof:top-k-by(  $input  as item()*,  $key    as fn(item()) as item(),  $k      as xs:integer) as item()*
SummaryReturns the $k items in $input that are greatest when sorted by the result of $key applied to the item. The function is a much more efficient implementation of the following scheme:
let $results := (
  for $item in $input
  order by $key($item) descending
  return $item
)
return subsequence($results, 1, $k)
Examples
hof:top-k-by(1 to 1000, identity#1, 5)
Result: 1000, 999, 998, 997, 996
hof:top-k-by(1 to 1000, fn { -. }, 3)
Result: 1, 2, 3
hof:top-k-by(<x a='1' b='2' c='3'/>/@*, xs:integer#1, 2)/local-name()
Result: 'c', 'b'

hof:top-k-with

Signature
hof:top-k-with(  $input       as item()*,  $comparator  as fn(item(), item()) as xs:boolean,  $k           as xs:integer) as item()*
SummaryReturns the $k items in $input that are greatest when sorted in the order of the less-than predicate $comparator. The function is a general version of hof:top-k-by.
Examples
hof:top-k-with(1 to 1000, fn($a, $b) { $a lt $b }, 5)
Result: 1000, 999, 998, 997, 996
hof:top-k-with(-5 to 5, fn($a, $b) { abs($a) gt abs($b) }, 5)
Result: 0, 1, -1, 2, -2

Changelog

Version 13.0
  • Removed: hof:scan-left (replaced with fn:scan)
Version 11.0Version 9.5
  • Added: hof:drop-while
Version 8.1
  • Added: hof:scan-left, hof:take-while
Version 7.2Version 7.0
  • Added: New module added.

⚡Generated with XQuery