kdb+k

Sum of each two elements using vector functions


How to get sum of eath two elements with the vector functions? I want the same result as:

{x+y}':[1 2 3 2 1]

Why this approach gives something different than first one?

sum':[1 2 3 2 1]

Solution

  • sum is not the same as {x+y}.

    sum has rank 1 meaning it takes one input and sums the elements of that input.

    It can sum an atom:

    q)sum 1
    1
    

    a uniform list

    q)sum 1 2
    3
    

    or a list of lists

    q)sum(1 2;3 4)
    4 6
    

    {x+y} is rank 2 meaning it requires two inputs.

    q){x+y}[1;2]
    3
    q){x+y}[1 2;3 4]
    4 6
    

    Giving it an atom, a single list, or a list of lists leads to projections

    q){x+y}1
    {x+y}[1]
    q){x+y}1 2
    {x+y}[1 2]
    q){x+y}(1 2;3 4)
    {x+y}[(1 2;3 4)]
    

    Since each-prior (':) creates binary pairs from the input and attempts to apply a rank 2 function, it works as intended on your rank 2 function {x+y}.

    But since sum is not rank 2 the each-prior doesn't generate pairs in the same way, it's equivalent to doing

    q){x}':[1 2 3 2 1]
    1 2 3 2 1
    q){sum x}':[1 2 3 2 1]
    1 2 3 2 1
    

    You could force it to be rank 2:

    q){sum(x;y)}':[1 2 3 2 1]
    1 3 5 5 3
    

    but this gives a different result since sum ignores nulls while + doesn't.

    q)sum(0N;1)
    1
    q)0N+1
    0N
    

    Finally, an alternative way to achieve this using sum (and without using each-prior) is to shift the vector using prev and then sum

    q){sum(prev x;x)}[1 2 3 2 1]
    0N 3 5 5 3