Last active
March 2, 2023 19:23
-
-
Save line-o/4f06be97455ec9e1049da5785ab372f9 to your computer and use it in GitHub Desktop.
A safe way to evaluate the effective boolean value of a sequence of items -> anything that cannot be evaluated is false
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
xquery version "3.1"; | |
declare function local:safe-effective-boolean-value-if ( | |
$result as item()* | |
) as xs:boolean { | |
try { | |
if ($result) | |
then true() | |
else false() | |
} catch err:FORG0006 { | |
false() | |
} | |
}; | |
declare function local:safe-effective-boolean-value-boolean ( | |
$result as item()* | |
) as item()* { | |
try { | |
boolean($result) | |
} catch err:FORG0006 { | |
false() | |
} | |
}; | |
declare function local:safe-effective-boolean-value-not2 ( | |
$result as item()* | |
) as item()* { | |
try { | |
not(not($result)) | |
} catch err:FORG0006 { | |
false() | |
} | |
}; | |
(: must evaluate to true :) | |
declare variable $local:positive := [ | |
1, | |
1.2, | |
"0", | |
"false", | |
"value", | |
("value"), | |
true(), | |
<a />, | |
attribute a { "b" }, | |
xs:double("1") | |
]; | |
(: must evaluate to false :) | |
declare variable $local:negative := [ | |
(), | |
0, | |
xs:double("0"), | |
"", | |
[], | |
function(){}, | |
map{}, | |
(1,2,3), | |
(true(), false()), | |
false(), | |
xs:date("1970-01-01"), | |
xs:dateTime("1970-01-01T00:00:00"), | |
xs:double("NaN") | |
]; | |
declare function local:assert-positives ($f as function(*)) as xs:boolean { | |
array:for-each($local:positive, $f) | |
=> array:fold-left(true(), function ($a, $b) { $a and $b }) | |
}; | |
declare function local:assert-negatives ($f as function(*)) as xs:boolean { | |
array:for-each($local:negative, $f) | |
=> array:fold-left(false(), function ($a, $b) { $a or $b }) | |
=> not() | |
}; | |
map { | |
"safe-effective-boolean-value-if": map { | |
"positives": local:assert-positives(local:safe-effective-boolean-value-if#1), | |
"negatives": local:assert-negatives(local:safe-effective-boolean-value-if#1) | |
}, | |
"safe-effective-boolean-value-boolean": map { | |
"positives": local:assert-positives(local:safe-effective-boolean-value-boolean#1), | |
"negatives": local:assert-negatives(local:safe-effective-boolean-value-boolean#1) | |
}, | |
"safe-effective-boolean-value-not2": map{ | |
"positives": local:assert-positives(local:safe-effective-boolean-value-not2#1), | |
"negatives": local:assert-negatives(local:safe-effective-boolean-value-not2#1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment