If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Friday, March 22, 2013

XQuery3.0: Mimicking a FLWOR expression with higher-order functions

xquery version "3.0";
declare function local:flwor(
$ctxt as item(),
$find as function(item()) as item()*,
$predicate as function(item()) as xs:boolean,
$orderBy as function(item()) as item()) as item()* {
for $result in $find($ctxt)
where $predicate($result)
order by $orderBy($result)
return $result
};
declare function local:isMale($person as element(person)) as xs:boolean {
$person/@gender = 'male'
};
declare function local:getPersons($persons as element(persons)) as element(person)* {
$persons/person
};
let $persons :=
<persons>
<person gender="male">
<country>Belgium</country>
<name>John</name>
<age>10</age>
</person>
<person gender="male">
<country>Netherlands</country>
<name>Robby</name>
<age>20</age>
</person>
<person gender="female">
<country>Belgium</country>
<name>Linda</name>
<age>80</age>
</person>
<person gender="male">
<country>Belgium</country>
<name>Davy</name>
<age>40</age>
</person>
<person gender="female">
<country>Netherlands</country>
<name>Alice</name>
<age>30</age>
</person>
<person gender="male">
<country>Netherlands</country>
<name>Albert</name>
<age>36</age>
</person>
</persons>
let $getPersons := local:getPersons#1
let $isMale := local:isMale#1
return local:flwor(
$persons,
$getPersons,
$isMale,
function($person as element(person)) as item() { $person/name}
)
(:
****************************************************************
XQuery output: We expect a sequence of all males ordered by name
****************************************************************
<person gender="male">
<country>Netherlands</country>
<name>Albert</name>
<age>36</age>
</person>
<person gender="male">
<country>Belgium</country>
<name>Davy</name>
<age>40</age>
</person>
<person gender="male">
<country>Belgium</country>
<name>John</name>
<age>10</age>
</person>
<person gender="male">
<country>Netherlands</country>
<name>Robby</name>
<age>20</age>
</person>
:)

No comments:

Post a Comment