Mark Ireland
Mark Ireland

Reputation: 175

Alternating (interleaving?) two XQuery For loops

If a=A,B,C and b=1,2,3 then in XQuery I can have consecutive loops like:

{for $x in a
return $x}

{for $y in b
return $y}

which would return A,B,C,1,2,3

Or I could have nested loops like:

{for $x in a
return $x
    for $y in b
    return $y}}

which would return A1, A2, A3, B1, B2, B3, C1, C2, C3 (or maybe the other way around, but you know what I mean).

However, what I need is to return A,1,B,2,C,3

I'm struggling to see a way to have two loops but alternate the results of them in my output. Any suggestions? I've searched for a solution, but I'm no XQuery expert and I'm not even sure I'm using the correct terminology.

Upvotes: 1

Views: 91

Answers (2)

Leo Wörteler
Leo Wörteler

Reputation: 4241

In XQuery 3.0 there is the higher-order function fn:for-each-pair($seq1, $seq2, $f) which applies a user-supplied function to the first, second etc. item of the two input sequences $f($seq1[1], $seq2[1]), $f($seq1[2], $seq2[2]), ... until one of the sequences is exhausted. For your use case you just want sequence concatenation:

fn:for-each-pair(('A', 'B', 'C'), (1, 2, 3), function($a, $b) { $a, $b })

Upvotes: 3

wst
wst

Reputation: 11771

You can use the position of the iterator in the first sequence to get the value at the same position in the second sequence:

for $x at $pos in a
let $y := b[$pos]
return ($x, $y)

Upvotes: 1

Related Questions