2

I'm struggling to understand this q code programming idiom from the kx cookbook:

q)swin:{[f;w;s] f each { 1_x,y }\[w#0;s]}
q)swin[avg; 3; til 10]
0 0.33333333 1 2 3 4 5 6 7 8

The notation is confusing. Is there an easy way to break it down as a beginner?

I get that the compact notation for the function is probably equivalent to this

swin:{[f;w;s] f each {[x; y] 1_x, y }\[w#0;s]}

w#0 means repeat 0 w times (w is some filler for the first couple of observations?), and 1_x, y means join x, after dropping the first observation, to y. But I don't understand how this then plays out with f = avg applied with each. Is there a way to understand this easily?

Thomas Smyth - Treliant
  • 4,993
  • 6
  • 25
  • 36

1 Answers1

3

http://code.kx.com/q/ref/adverbs/#converge-iterate

Scan (\) on a binary (two-param) function takes the first argument as the seed value - in this case 3#0 - and iterates through each of the items in the second list - in this case til 10 - applying the function (append new value, drop first).

q){1_x,y}\[3#0;til 10]
0 0 0
0 0 1
0 1 2
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9

So now you have ten lists and you can apply a function to each list - in this case avg but it could be any other function that applies to a list

q)med each {1_x,y}\[3#0;til 10]
0 0 1 2 3 4 5 6 7 8f
q)
q)first each {1_x,y}\[3#0;til 10]
0 0 0 1 2 3 4 5 6 7
q)
q)last each {1_x,y}\[3#0;til 10]
0 1 2 3 4 5 6 7 8 9
terrylynch
  • 11,844
  • 13
  • 21