Skip to content

Instantly share code, notes, and snippets.

@line-o
Created May 25, 2018 10:37
Show Gist options
  • Select an option

  • Save line-o/254e0d20c86200fc03ffa6f49bf552e4 to your computer and use it in GitHub Desktop.

Select an option

Save line-o/254e0d20c86200fc03ffa6f49bf552e4 to your computer and use it in GitHub Desktop.
Some examples how to work with sequences and the arrow operator using a bit of meta programming.
xquery version "3.1";
(:~
: some examples how to work with sequences and the arrow operator
: using a bit of meta programming
~:)
(: can be used within a for-each or a local:map :)
declare function local:plusOne ($a as xs:integer) { $a + 1 };
declare function local:greaterThan ($n as xs:integer, $a as xs:integer) { $a > $n };
(: reducing the number of ? by returning a function instead :)
declare function local:greaterThanThatReturnsAFunction ($n as xs:integer) {
local:greaterThan($n, ?)
};
(: meta functions that result in one less question mark in the code :)
declare function local:map ($f as function(*)) { for-each(?, $f) };
declare function local:filterBy ($rule as function(*)) { filter(?, $rule) };
declare function local:take ($n as xs:integer) { subsequence(?, 1, $n) };
(: this type of writing the function enables to use it directly after the arrow :)
declare function local:ascending ($s) { sort($s, (), function ($a) { -$a }) };
(: example usage :)
(0 to 9)
(:
: it turns out, for-each and filter can be used \o/
: ParenthesizedExpr(ession) FTW
:)
=> (for-each(?, local:plusOne#1))(?)
(: one less ? using local:map :)
=> (local:map(local:plusOne#1))(?)
(: filter by rule which itself is a partially applied function :)
=> (local:filterBy(local:greaterThan(5, ?)))(?)
(: using functions from external modules :)
=> (local:map(math:pow(?, 2)))(?)
(: filter by using the function returning rule :)
=> (local:filterBy(local:greaterThanThatReturnsAFunction(10)))(?)
(: only a single ? and no parenthesis needed here :)
=> local:ascending(?)
(: return the first item in the sequence :)
=> (local:take(1))(?)
(: should return 1.21e2 AKA 121 :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment