Search code examples
kdb

q/KDB - nprev function to get all the previous n elements


I am struggling to write a nprev function in KDB; xprev function returns the nth element but I need all the prev n elements relative to the current element.

q)t:([] i:1+til 26; s:.Q.a)

q)update xp:xprev[3;]s,p:prev s from t

Any help is greatly appreciated.


Solution

  • The xprev function basically looks like this :

    xprev1:{y til[count y]-x}    //readable xprev
    

    We can tweak it to get all n elements

    nprev:{y til[count y]-\:1+til x}
    

    using nprev in the query

    q)update np: nprev[3;s] , xp1:xprev1[3;s] , xp: xprev[3;s], p:prev[s]  from t
    i  s np    xp1 xp p
    -------------------
    1  a "   "         
    2  b "a  "        a
    3  c "ba "        b
    4  d "cba" a   a  c
    5  e "dcb" b   b  d
    6  f "edc" c   c  e
    

    k equivalent of nprev

    k)nprev:{$[0h>@y;'`rank;y(!#y)-\:1+!x]}
    

    and similarly nnext would look like

    k)nnext:{$[0h>@y;'`rank;y(!#y)+\:1+!x]}