Reputation: 51
I am learning the Q programming language because my new job will require it. I am doing some practice exercises and am wondering whether it is possible to imitate a nested loop using the "each" keyword.
For example, I know that:
f:{x*x}
a:(1;2;3;4;5)
f each a -> 1 4 9 16 25j
However, lets say for instance that I want to imitate a nested for loop to multiply the values of two lists. If we have:
a:(1;2;3;4;5)
b:(1;2;3;4;5)
In conventional java, this would be done by:
for(int i = 0; i < a.length; i++) {
for(int j = 0; j < b.length; j++) {
System.out.println(a[i]*b[j]);
}
}
Is it possible to imitate this nested for loop structure using "each" in q?
Upvotes: 0
Views: 606
Reputation: 1593
You can achieve this using iterators (formerly adverbs) in kdb EG
a*/:b // Each Right
Will multiply each element of b by every element of a. In this case it would be as if you were iterating through b in your outer loop and a in your inner loop.
You could flip this to
a*\:b // Each Left
Which would have a in your outer loop and b in your inner loop. If a and b are the same length and you would like to multiply element-wise then you can do a simple
a*b
For more on iterators: https://code.kx.com/q/wp/iterators/
Upvotes: 3