if¶
Evaluate expressions under some condition
if[test;e1;e2;e3;…;en]
Control construct. Where
testis an expression that evaluates to an atom of integral type, typically a booleane1,e2, …enare expressions
unless test evaluates to zero, q evaluates the expressions e1 to en in order.
The result of if is always the generic null.
q)a:100
q)r:""
q)if[a>10;a:20;r:"true"]
q)a
20
q)r
"true"
A null integer is not zero, so it counts as true.
q)if[0N;r:"null"]
q)r
"null"
if is not a function but a control construct. You cannot iterate or project it.
Prefer if to Cond when a test guards a side effect, such as amending a global variable.
A common use is to catch special or invalid arguments to a function.
foo:{[x;y]
if[type[x]<0; :x]; / no-op for atom x
if[count[y]<>3; '"length"]; / invalid y
..
}
Name scope¶
The brackets of the expression list do not create lexical scope. Name scope within the brackets is the same as outside them.
Setting local variables using if can have unintended consequences.
Cond,
do,
while,
Vector Conditional
Q for Mortals
§10.1.5 if