bool
bool is the type of the two values true and false. Conditions, the logical operators, comparisons, and predicates all use it.
Details
boolhas no truthiness. A condition,!,&&,||, andasserttake aboolonly, and a number, a string, or a nullable value there is a compile error: give abool | nulla default with??first.booldoes not convert to or from a number or a string.int(true)is a compile error, and noStringfunction parses"true": compare instead, such asn != 0ors == "true".boolvalues have no order.==and!=compare them;<andArray.sortdo not apply.boolrenders astrueorfalse, in a string, throughprintln, and inside a container.
Basic examples
A literal, a comparison, and a function that answers a question all give a bool:
let ready: bool = true
ready // true
3 > 2 // true
"ant".isEmpty() // falsebool in a string:
let done = false
"done: ${done}" // "done: false"Scope
Predicates
A function that returns bool is a predicate. Its type, func(T): bool, is what filter, some, every, and find take. To negate a predicate, put ! inside a lambda that calls it:
func isEven(n: int): bool { n % 2 == 0 }
let xs = [1, 2, 3, 4]
xs.filter(isEven) // [2, 4]
xs.filter({ !isEven(x) }) // [1, 3]
xs.some({ x > 3 }) // true
xs.countWhere(isEven) // 2Record fields and named arguments
A bool parameter often has a default, so a caller names it only to change it:
func greet(name: string, shout: bool = false): string {
if shout { name.toUpper() } else { name }
}
greet("ann") // "ann"
greet("ann", shout: true) // "ANN"For several flags, an options record with bool fields keeps the call short:
type Options = { verbose: bool = false, dryRun: bool = false }
func run(task: string, opts: Options = Options{}): string {
let prefix = if opts.dryRun { "would run" } else { "running" }
"${prefix} ${task}"
}
println(run("build"))
println(run("deploy", opts: Options{ dryRun: true }))running build
would run deployCollections
bool works as an array element, a map key, and a set member. groupBy on a predicate splits an array into the elements it accepts and the rest:
let groups = [1, 2, 3, 4, 5].groupBy({ x % 2 == 0 })
groups[true] // [2, 4]
groups[false] // [1, 3, 5]
Set.of([true, true, false]) // Set.of([true, false])Nullable booleans
bool | null has three states. ?? picks the default for the missing one:
let settings: Map[string, bool] = Map{ "color": false }
settings["color"] ?? true // false
settings["debug"] ?? true // trueIn a union
is bool picks the bool member of a union, such as a JSON value:
func describe(v: Json.Value): string {
if v is bool { return if v { "yes" } else { "no" } }
String.from(v)
}
let parsed = Json.parse(`[true, 1, false]`) | Result.unwrap()
if parsed is Array {
println(parsed.map(describe) | String.join(", "))
}yes, 1.0, noNamed types over bool
A type declaration over bool makes a distinct type. Its constructor tags a value, and bool(x) gives the plain bool back:
type Consent = bool
let accepted = Consent(true)
accepted // Consent(true)
bool(accepted) // true
accepted == Consent(true) // trueApplications
Toggling a flag
var lightOn = false
for _ in Iter.range(0, 3) {
lightOn = !lightOn
println(lightOn)
}true
false
trueReading a yes-or-no answer
String has no function that parses a bool, so compare the text:
func answer(text: string): bool | null {
let word = text.trim().toLower()
if word == "yes" || word == "y" { return true }
if word == "no" || word == "n" { return false }
null
}
answer(" Yes ") // true
answer("n") // false
answer("maybe") // nullProperties and relations
Double negation gives the value back, and comparing a bool with true gives the same bool:
for b in [true, false] {
assert(!!b == b)
assert((b == true) == b)
assert((b != false) == b)
assert(String.from(b) == (if b { "true" } else { "false" }))
}
println("ok")okPossible issues
A number is not a condition
let count = 3
if count { println("some") } // error: cannot use int where bool is expectedCompare instead:
let count = 3
count > 0 // truebool does not convert to a number
let n = int(true) // error: int converts a number or a named primitive type over a number, got boolCount with countWhere, or choose with if:
let flags = [true, false, true]
flags.countWhere({ x }) // 2
if flags[1] { 1 } else { 0 } // 0bool values cannot be sorted
Array.sort needs an ordered type. Sort by an int key instead:
let flags = [true, false, true]
let sorted = flags.sort() // error: T would be bool, which is not a member of its bound Orderedlet flags = [true, false, true]
flags.sortBy({ if x { 1 } else { 0 } }) // [false, true, true]A nullable bool is not a condition
let flag: bool | null = null
if flag { println("on") } // error: cannot use bool | null where bool is expectedlet flag: bool | null = null
flag ?? false // falseA named type over bool is not a bool
type Consent = bool
let accepted = Consent(true)
if accepted { println("ok") } // error: cannot use Consent where bool is expectedUnwrap it with bool(accepted).
