0

From KX: https://code.kx.com/q/ref/value/ says, when x is a list, value[x] will be result of evaluating list as a parse tree.


Q1. In code below, I understand (A) is a parse tree, given below definition. However, why does (B) also work? Is ("+";3;4) a valid parse tree?

q)value(+;3;4)  / A
7
q)value("+";3;4)  / B
7
q)eval(+;3;4) / C
7
q)eval("+";3;4) / D
'length
  [0]  eval("+";3;4)

Any other parse tree takes a form of a list, of which the first item is a function and the remaining items are its arguments. Any of these items can be parse trees. https://code.kx.com/q/basics/parsetrees/


Q2. In below code, value failed to return the result of what I think is a valid parse tree, but eval works fine, recursively evaluating the tree. Does this mean the topmost description is wrong?

q)value(+;3;(+;4;5))
'type
  [0]  value(+;3;(+;4;5))
       ^
q)eval(+;3;(+;4;5))
12

Q3. In general then, how do we choose whether to use value or eval?

kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80

1 Answers1

5

put simply the difference between eval and value is that eval is specifically designed to evaluate parse trees, whereas value works on parse trees among other operations it does. For example value can be used to see the non-keyed values of dictionaries, or value strings, such as:

q)value"3+4"
7

Putting this string instead into the eval, we simply get the string back:

q)eval"3+4"
"3+4"

1 Following this, the first part of your question isn't too bad to answer. The format ("+";3;4) is not technically the parsed form of 3+4, we can see this through:

q)parse"3+4"
+
3
4

The good thing about value in this case is that it is valuing the string "+" into a the operator + and then valuing executing the parse tree. eval cannot understand the string "+" as this it outside the scope of the function. Which is why A, B and C work but not D.

2 In part two, your parse tree is indeed correct and once again we can see this with the parse function:

q)parse"3+(4+5)"
+
3
(+;4;5)

eval can always be used if your parse tree represents a valid statement to get the result you want. value will not work on all parse tree's only "simple" ones. So the nested list statement you have here cannot be evaluated by value.

3 In general eval is probably the best function of choice for evaluating your parse trees if you know them to be the correct parse tree format, as it can properly evaluate your statements, even if they are nested.

matthewclark
  • 144
  • 3