Skip to content

if

Evaluate expression/s under some condition

if[test;e1;e2;e3;…;en]

Control construct. Where

  • test is an expression that evaluates to an atom of integral type
  • e1, e2, … en are expressions

unless test evaluates to zero, the expressions e1 to en are evaluated, 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"

if is not a function but a control construct. It cannot be iterated or projected.

if is often preferred to Cond when a test guards a side effect, such as amending a global.

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
Controlling evaluation
Q for Mortals §10.1.4 if