In q/kdb+, what does 2*3+4 evaluate to, and why isn't it 10?
In q/kdb+, what does 2*3+4 evaluate to, and why isn't it 10?
In q/kdb+, what does 2*3+4 evaluate to, and why isn't it 10?
2*3+4 evaluates to 14, not 10.
The reason is that q has no operator precedence. Every function and operator has the same precedence, and expressions are evaluated right to left (q docs call this "left-of-right"). So * does not bind tighter than +. The rightmost operation runs first:
3+4 → 72*7 → 14In other words, q reads 2*3+4 as 2*(3+4), whereas a conventional precedence-based language reads it as (2*3)+4 = 10. The general rule from the q documentation: a*b+c is a*(b+c), not (a*b)+c.
To get 10 you must parenthesize the left operand explicitly:
q)2*3+4
14
q)(2*3)+4
10
A practical consequence: if the left operand of an operator is itself an expression, it must be wrapped in parentheses, otherwise the operator binds only to the right-most element of the expression. This uniform right-to-left rule (inherited from q's APL/A+ lineage) lets q chain operations cleanly without precedence tables, much like piping data from right to left. Note one exception to right-to-left: within function bodies, conditionals, and control statements, the separate semicolon-delimited expressions are run left to right.
Sources: