Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[KDB+/Q]: Apply list of functions over data sequentially (pipe)

In kdb+/q, how to pipe data through a sequential list of functions so that output of previous step is the input to next step?

For example:

q)t:([]sym:`a`c`b;val:1 3 2)
q)`sym xkey `sym xasc t                / how to achieve the same result as this?

I presume some variation of over or / could work:

   ?? over (xasc;xkey)

Bonus: how to achieve the same in a way where t is piped in from the right-hand side (in the spirit of left-of-right reading of the q syntax)?

(xasc;xkey) ?? t
like image 514
Daniel Krizian Avatar asked Jan 03 '23 15:01

Daniel Krizian


2 Answers

how to pipe data through a sequential list of functions so that output of previous step is the input to next step?

You can use the little known composition operator. For example:

q)f:('[;])over(2+;3*;neg)
q)f 1 # 2+3*neg 1
-1

If you want to use the left of right syntax, you will have to define your own verb:

q).q.bonus:{(('[;])over x)y}
q)(2+;3*;neg)bonus 1
-1
like image 130
Alexander Belopolsky Avatar answered Feb 16 '23 13:02

Alexander Belopolsky


Use a lambda on the left as well as the over adverb (form of recursion) Also the dot (.) form of apply is used to apply the function to the table and the column:

  {.[y;(z;x)]}/[t;(xasc;xkey);`sym]
  sym| val
  ---| --- 
  a  | 1
  b  | 2
  c  | 3
like image 41
jomahony Avatar answered Feb 16 '23 13:02

jomahony