Last active
December 5, 2023 19:48
-
-
Save line-o/ee8411e5a28280854b169f5cd0f7c829 to your computer and use it in GitHub Desktop.
Python like zip function in Xquery
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
import module namespace array="http://www.w3.org/2005/xpath-functions/array"; | |
import module namespace map="http://www.w3.org/2005/xpath-functions/map"; | |
declare namespace _="//line-o.de/ns/underline"; | |
declare function _:nth-item ($sequence as item()*, $pos as xs:integer) as item()* { | |
$sequence[$pos] | |
}; | |
declare function _:reduce-sequences ( | |
$result as array(*)*, | |
$pos as xs:integer, | |
$array-of-sequences as array(*) | |
) as array(*)* { | |
$result, | |
array:for-each($array-of-sequences, _:nth-item(?, $pos)) | |
}; | |
declare function _:sequences ($array-of-sequences as array(*)) as array(*)* { | |
fold-left(1 to count($array-of-sequences?1), (), | |
_:reduce-sequences(?, ?, $array-of-sequences)) | |
}; | |
declare function _:append-nth-member ($res as array(*), $arr as array(*), $pos as xs:integer) as array(*) { | |
array:append($res, if ($pos > array:size($arr)) then () else $arr($pos)) | |
}; | |
declare function _:fold-arrays ( | |
$result as array(*)*, $pos as xs:integer, $sequence-of-arrays as array(*)+ | |
) as array(*)* { | |
$result, | |
fold-left($sequence-of-arrays, [], _:append-nth-member(?, ?, $pos)) | |
}; | |
declare function _:arrays ($sequence-of-arrays as array(*)+) as array(*)+ { | |
fold-left(1 to array:size(head($sequence-of-arrays)), (), | |
_:fold-arrays(?, ?, $sequence-of-arrays)) | |
}; | |
declare function _:zip ($sequence-or-array) as array(*)* { | |
typeswitch ($sequence-or-array) | |
case array(*) return _:sequences($sequence-or-array) | |
default return _:arrays($sequence-or-array) | |
}; | |
"------- array of sequences 1: translations -------", | |
_:zip(( | |
array{ 1 to 3 }, | |
["one", "two", "three"], | |
["un", "deux", "trois"], | |
["eins", "zwei", "drei"], | |
["yksi", "kaksi", "kolme"] | |
)), | |
"------- array of sequences 2: short first -------", | |
_:zip((["a", "b"], [1, 2, 3], [<m/>, <n/>, <o/>, <p/>])), | |
"------- array of sequences 3: long first -------", | |
_:zip((["a", "b", "c", "d"], [1, 2, 3], [<m/>, <n/>])), | |
"------- sequence of arrays 1: translations -------", | |
_:zip([ | |
(1 to 3), | |
("one", "two", "three"), | |
("un", "deux", "trois"), | |
("eins", "zwei", "drei"), | |
("yksi", "kaksi", "kolme") | |
]), | |
"------- sequence of arrays 2: short first -------", | |
_:zip([("a", "b"), (1, 2, 3), (<m/>, <n/>, <o/>, <p/>)]), | |
"------- sequence of arrays 3: long first -------", | |
_:zip([("a", "b", "c", "d"), (1, 2, 3), (<m/>, <n/>)]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment