0

How to extract and manipulate parse tree of a lambda/function?

E.g. given the function

pair:{` sv x,y}'

I'd like to arrive at the "inverse" version using a combinator called inverse so that the following call returns (note the now swapped order of x and y):

q)inverse pair
{` sv y,x}'

The following works on embedded q functions and qsql, but not user-defined lambdas:

q)-3!parse "mavg"
"k){msum[x;0.0^y]%mcount[x;y]}"
q)-3!parse "select avg foo,sum bar by blah from myTable"
"(?;`myTable;();(,`blah)!,`blah;`foo`bar!((avg;`foo);(sum;`bar)))"
q) parse "pair"
`pair
q)-3!parse string pair
"(';{` sv x,y})"

Thanks

Daniel Krizian
  • 4,586
  • 4
  • 38
  • 75

2 Answers2

3

Is this what you mean or am I missing something?

q)inverse:{x[z;y]}
q)pair:{` sv x,y}'
q)pair[`b;`a]
`b.a
q)pair[`a;`b]
`a.b
q)inverse[pair][`a;`b]
`b.a
q)pair[`b`gg;`a`ff]
`b.a`gg.ff
q)inverse[pair][`b`gg;`a`ff]
`a.b`ff.gg

It may be considered more idiomatic to use the ability to apply functions to lists as arguments, then use the builtin list manipulators to reorder the arguments like so:

q)f . 2 3
0.6666667
q)f . reverse 2 3
1.5
q)g:{x+y%z}
q)g . 1 2 3
1.666667
q)g . reverse 1 2 3
5f
q)g . 1 rotate reverse 1 2 3
2.333333
Ryan Hamilton
  • 2,601
  • 16
  • 17
2

For a regular function/lambda (type 100h) you can use "value" to extract useful information about the function, including the string of the definition.

q)value[mavg]
0x7978820a0279a04778810a02440004
`x`y
`symbol$()
`q`msum`mcount
0f
"k){msum[x;0.0^y]%mcount[x;y]}"

q)pair2:{` sv x,y}
q)value pair2
0x79784c0fa00a020003
`x`y
`symbol$()
,`
k){x/:y}
"{` sv x,y}"

q)last value pair2
"{` sv x,y}"

q)last value {x+y}
"{x+y}"

Your pair is a type 106h though, so doesn't behave the same

terrylynch
  • 11,844
  • 13
  • 21