if is a two-branch conditional expression controlled by a Boolean test.
Syntax
(if ⟨test-expr⟩ ⟨then-expr⟩ ⟨else-expr⟩)
Semantics
⟨test-expr⟩,⟨then-expr⟩, and⟨else-expr⟩are all required; each is a single expression (not an implicitprogn).⟨test-expr⟩must have typeBoolean.⟨test-expr⟩is evaluated first:- If it evaluates to
True,⟨then-expr⟩is evaluated and its value(s) are returned (⟨else-expr⟩is not evaluated). - If it evaluates to
False,⟨else-expr⟩is evaluated and its value(s) are returned (⟨then-expr⟩is not evaluated).
- If it evaluates to
⟨then-expr⟩and⟨else-expr⟩must unify to the same type, which may be a single value,Void, or multiple values.- Both
⟨then-expr⟩and⟨else-expr⟩are in tail position when theifexpression is in tail position (including forrectail calls).
Examples
(coalton-toplevel
(declare abs-int (Integer -> Integer))
(define (abs-int n)
(if (< n 0)
(negate n)
n))
;; Returning multiple values from `if` branches
(declare ordered-pair (Integer * Integer -> Integer * Integer))
(define (ordered-pair a b)
(if (<= a b)
(values a b)
(values b a))))
Other Notes
- By Coalton style convention,
ifis used for pure two-way expressions. When branches require multiple statements, localletbindings, or side effects, or when chaining multiple tests, prefercond. For one-armed side-effecting conditionals, usewhenorunless. - In release mode, locally bound data types, structs, and
Cells constructed acrossifbranches can be scalar-replaced or unboxed without heap allocation. See Performance and Optimization.