Search code examples
for-loopwhile-loopiteratoriterationkdb+

kdb/Q How to iterate on a function x number of times?


I'm new to kdb/Q, what is the equivalent of iteration, where I need to run a function 10 times?

In Python, it would be something like creating some kind of iterator, using a while loop to run the function and add 1 to the iterator, and stopping when the iterator has reached 10.


Solution

  • The native approach is to use accumulators/iterators/over/scan as per: https://code.kx.com/q/ref/accumulators/#do

    q){x+1}/[10;1000]
    1010
    q)
    q){x+1}\[10;1000]
    1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    

    e.g. run {x+1} 10 times with a starting value of 1000

    There is also a do keyword which is useful for performing an operation N times without needing to carrying the output from one run the next: https://code.kx.com/q/ref/do/