Main Page » XQuery » Functions » Higher-Order Functions

Higher-Order Functions

This module adds some useful higher-order functions, additional to the standard Higher-Order Functions provided by the official specification.

Removed: Some functions have been removed in favor of new XQuery 4 standard functions:

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 in this module are assigned to the http://basex.org/modules/hof namespace, which is statically bound to the hof prefix.

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 $seq has to be non-empty.

hof:scan-left

Signature
hof:scan-left(
  $input   as item()*,
  $zero    as item()*,
  $action  as fn(item()*, item()) as item()*
) as item()*
SummaryThis function is similar to fn:fold-left, but it returns a list of successive reduced values from the left. It is equivalent to:
declare function hof:scan-left($input, $acc, $action) {
  if (empty($input)) then $acc else (
    $acc,
    hof:scan-left(tail($input), $action($acc, head($input)), $action)
  )
};
Examples
hof:scan-left(1 to 5, 0, op('+'))
Result: 0, 1, 3, 6, 10, 15. Computes triangular numbers.

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 11.0Version 9.5
  • Added: hof:drop-while
Version 8.1Version 7.2Version 7.0
  • Added: The module was added with Version 7.0.

⚡Generated with XQuery