[KDB+/Q]: Deparse q parse tree into q expression (string)

若如初见. 提交于 2020-01-15 11:14:03

问题


Let's define deparse1 as inverse operation to q's native parse, so that the following holds:

q)aStringQExpression~deparse parse aStringQExpression
1b

Question

What's the definition of deparse function so that the above indeed works?

For example, in the below update expression, we know that "a*0^b+c-d" expression corresponds to (*;`a;(^;0;(+;`b;(-;`c;`d)))) parse tree:

q)-3!parse "update col:a*0^b+c-d from t"
"(!;`t;();0b;(,`col)!,(*;`a;(^;0;(+;`b;(-;`c;`d)))))"

So the envisaged deparse function should return:

q)deparse "(*;`a;(^;0;(+;`b;(-;`c;`d))))"
"a*0^b+c-d"
q)deparse "(!;`t;();0b;(,`col)!,(*;`a;(^;0;(+;`b;(-;`c;`d)))))"
"update col:a*0^b+c-d from t"

Motivation/Background/Use case: Inline expressions are arguably faster to grok by human eye (left-to-right) than deeply nested parse trees. Although in the background my code is editing the parse tree programatically, it is useful for debugging or presentation to conveniently convert that resulting parse tree into inline expression string.


1 Similar functionality described here: http://adv-r.had.co.nz/Expressions.html#parsing-and-deparsing


回答1:


I think the only way to do this would be to parse the list recursively and build up a string, e.g. for a dyadic:

q)deparse:{a:-3!'x;a[1],a[0],a[2]}
q)deparse parse "3*3"
"3*3"

So you can count last x to get it valency and build the string accordingly




回答2:


This unparse repository from Github solves the problem. Amazing:

q).unparse.unparse parse "update col:a*0^b+c-d from t"
"update col:(a*(0^(b+(c-d)))) from t"

q).unparse.unparse parse "a*0^b+c-d"
"(a*(0^(b+(c-d))))"


来源:https://stackoverflow.com/questions/44904518/kdb-q-deparse-q-parse-tree-into-q-expression-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!