&&, ||, and !
a && b is true when both operands are true. a || b is true when either operand is true. !a is the negation of a. All three take and give bool.
Details
&&and||short-circuit:a && bevaluatesbonly whenaistrue, anda || bonly whenaisfalse.- The operands must be
bool. There is no truthiness: anint, astring, or a nullable value is a compile error, not a test. &&binds tighter than||, and both bind looser than comparison and equality, soa < b && c == dneeds no parentheses.!is a prefix operator and binds tighter than all of them.??does not mix with&&or||without parentheses.- A null test or an
istest narrows the variable through&&,||, and!, so the right operand ofx != null && …seesxas non-null.
Basic examples
true && false // false
true || false // true
!true // falseComparisons combine without parentheses:
let age = 30
age >= 18 && age < 65 // true
age < 18 || age >= 65 // falseScope
Short-circuit evaluation
The right operand runs only when the left one does not decide the result:
func loud(name: string, value: bool): bool {
println("evaluated ${name}")
value
}
println(false && loud("right", true))
println(true || loud("right", true))
println(true && loud("right", false))false
true
evaluated right
falseGuarding the right operand
Short-circuiting lets the left operand protect the right one. Here xs[0] runs only when the array is not empty:
let xs: Array[int] = []
!xs.isEmpty() && xs[0] > 1 // falseNarrowing through && and ||
After name != null &&, the right operand sees name as a string. After name == null ||, it does too, since the right side runs only when the test failed:
let name: string | null = "Ann"
name != null && name.length() > 2 // true
name == null || name.isEmpty() // falseThe same holds for is on a union:
type Circle = { r: float64 }
type Square = { side: float64 }
type Shape = Circle | Square
func isLarge(s: Shape): bool {
s is Circle && s.r > 10.0 || s is Square && s.side > 10.0
}
println(isLarge(Circle{ r: 11.0 }))
println(isLarge(Square{ side: 4.0 }))true
falseGuards with ||
An if with || and an early return leaves the variable narrowed below it:
func describe(text: string | null): string {
if text == null || text.isEmpty() { return "empty" }
"${text.length()} characters"
}
println(describe(null))
println(describe(""))
println(describe("ant"))empty
empty
3 charactersNegating a test with !
! binds tighter than is, so a negated is test needs parentheses. It narrows like the test it negates:
type Circle = { r: float64 }
type Square = { side: float64 }
func area(s: Circle | Square): float64 {
if !(s is Circle) { return s.side * s.side }
3.0 * s.r * s.r
}
println(area(Square{ side: 2.0 }))
println(area(Circle{ r: 1.0 }))4.0
3.0! applies after a dot call, since postfix binds tighter than prefix:
let xs = [1, 2]
!xs.isEmpty() // trueNullable booleans
A bool | null is not a bool. Give it a default with ?? first, in parentheses when it meets && or ||:
let settings = Map{ "verbose": true }
let quiet = false
!(settings["verbose"] ?? false) // false
(settings["debug"] ?? false) || quiet // falseApplications
Leap years
&& binds tighter than ||, so the rule reads as written:
func isLeap(year: int): bool {
year % 4 == 0 && year % 100 != 0 || year % 400 == 0
}
[1900, 2000, 2024, 2025].filter(isLeap) // [2000, 2024]Filtering on several conditions
type Order = { customer: string, paid: bool, total: int }
let orders = [
Order{ customer: "Ann", paid: true, total: 120 },
Order{ customer: "Bob", paid: false, total: 300 },
Order{ customer: "Eve", paid: true, total: 40 },
]
orders
| Array.filter({ x.paid && x.total >= 100 })
| Array.map({ x.customer })
// ["Ann"]Validating input
func validUsername(name: string): bool {
let size = name.length()
size >= 3 && size <= 16 && !name.contains(" ")
}
println(validUsername("ant_dev"))
println(validUsername("al"))
println(validUsername("two words"))true
false
falseProperties and relations
De Morgan's laws hold for every pair of booleans, and each operator equals an if expression:
for a in [true, false] {
for b in [true, false] {
assert(!(a && b) == (!a || !b))
assert(!(a || b) == (!a && !b))
assert((a && b) == (if a { b } else { false }))
assert((a || b) == (if a { true } else { b }))
}
}
println("ok")okPossible issues
No truthiness
A number, a string, or a nullable value is not a condition. Compare it explicitly:
let count = 3
let ready = count && true // error: cannot use int where bool is expectedlet name: string | null = null
let shown = !name // error: cannot use string | null where bool is expectedlet count = 3
let name: string | null = null
count > 0 && name == null // trueMixing ?? with && or ||
let flag: bool | null = null
let on = flag ?? false || true // error: '??' cannot mix with '&&' or '||' without parenthesesAdd parentheses to say which you mean:
let flag: bool | null = null
(flag ?? false) || true // true
flag ?? (false || true) // true! binds tighter than is and ==
!s is Circle negates s, not the test:
type Circle = { r: float64 }
type Square = { side: float64 }
let s: Circle | Square = Circle{ r: 1.0 }
let notCircle = !s is Circle
// error: cannot use Circle | Square where bool is expected
// error: bool is never a Circle, so the test is always falseWrite !(s is Circle), and x != null instead of !x == null.
&& is not a statement shortcut
Both operands must be bool, so && cannot run a call for its effect. Use if:
let ok = true
ok && println("yes") // error: cannot use void where bool is expectedlet ok = true
if ok { println("yes") }yesNo ^, &&=, or ||=
Ant has no exclusive-or operator and no &&= or ||=. Two bools differ exactly when a != b, so != is exclusive or:
let a = true
let b = false
a != b // trueIn place of &&= and ||=, write the assignment out:
var ok = true
ok = ok && 3 > 5
ok = ok || 1 < 2
println(ok)trueA field does not narrow
Narrowing applies to locals, parameters, and top-level lets. A test on a field path does not narrow the right operand. Bind the field to a local first:
type User = { nickname: string | null }
let user = User{ nickname: "ant" }
let long = user.nickname != null && user.nickname.length() > 2
// error: string | null has no field or function length on every member: narrow the value firsttype User = { nickname: string | null }
let user = User{ nickname: "ant" }
let nickname = user.nickname
nickname != null && nickname.length() > 2 // true