Array.contains
func Array.contains[T](xs: Array[T], v: T): boolArray.contains reports whether some element of xs is == v.
Details
- Compares each element with
vby==, so arrays, maps, sets, and records match by contents. - An empty array gives
false. NaNequals nothing, itself included, so an array never containsNaN.
Basic examples
Array.contains([1, 2, 3], 2) // true
Array.contains([1, 2, 3], 5) // falseCall it through . on any array:
let fruit = ["apple", "pear", "plum"]
fruit.contains("pear") // true
fruit.contains("fig") // falseScope
An empty array contains nothing. Annotate it so that T is known:
let empty: Array[string] = []
empty.contains("") // falseStrings compare by code points. == does not normalize, so the two spellings of "é" differ:
let words = ["café", "naïve"]
words.contains("café") // true
words.contains("cafe\u{301}") // false
words.contains("CAFÉ") // falseRecords compare by tag and fields, so a fresh record with the same fields is found:
type Point = { x: int, y: int }
let path = [Point{ x: 0, y: 0 }, Point{ x: 1, y: 0 }, Point{ x: 1, y: 1 }]
path.contains(Point{ x: 1, y: 0 }) // true
path.contains(Point{ x: 0, y: 1 }) // falseMembers of a tagged union compare by tag and fields, so equal fields under another tag do not match:
type Circle = { size: float64 }
type Square = { size: float64 }
type Shape = Circle | Square
let shapes: Array[Shape] = [Circle{ size: 1.0 }, Square{ size: 2.0 }]
shapes.contains(Square{ size: 2.0 }) // true
shapes.contains(Circle{ size: 2.0 }) // falseA named primitive type compares its tag and its payload:
type UserId = string
let admins = [UserId("u-1"), UserId("u-7")]
admins.contains(UserId("u-7")) // trueNested arrays, maps, and sets compare by contents. Two maps or two sets are equal in any order:
[[1, 2], [3]].contains([3]) // true
[[1, 2], [3]].contains([2, 1]) // false
[Map{ a: 1, b: 2 }].contains(Map{ b: 2, a: 1 }) // true
[Set.of(["x", "y"])].contains(Set.of(["y", "x"])) // trueAn array whose element type includes null can look for null:
let scores: Array[int | null] = [90, null, 75]
scores.contains(null) // true
scores.contains(75) // trueIn a pipeline, the array is the first argument:
"the quick brown fox" | String.split(" ") | Array.contains("fox") // trueApplications
Drop stop words from a sentence:
let stop = ["a", "an", "the", "of"]
let words = "the art of an ant".split(" ")
words.filter({ !stop.contains(x) }) // ["art", "ant"]Accept only known values for an option:
func checkLevel(level: string): Result[string, string] {
if ["debug", "info", "warn", "error"].contains(level) {
Result.ok(level)
} else {
Result.err("unknown level: ${level}")
}
}
println(checkLevel("info"))
println(checkLevel("loud"))Ok{ value: "info" }
Err{ error: "unknown level: loud" }Walk a grid and stop at the first cell visited twice:
type Point = { x: int, y: int }
let moves = ["R", "U", "L", "D", "R"]
var at = Point{ x: 0, y: 0 }
let seen = [at]
for m in moves {
let dx = if m == "R" { 1 } else if m == "L" { -1 } else { 0 }
let dy = if m == "U" { 1 } else if m == "D" { -1 } else { 0 }
at = Point{ x: at.x + dx, y: at.y + dy }
if seen.contains(at) {
println("back at ${at}")
break
}
seen.push(at)
}back at Point{ x: 0, y: 0 }Properties and relations
Array.contains agrees with Array.indexOf, Array.some, and Set.has, which all compare by ==:
let xs = [3, 1, 4, 1, 5]
for v in [1, 2, 5] {
assert(xs.contains(v) == (xs.indexOf(v) != null))
assert(xs.contains(v) == xs.some({ x == v }))
assert(xs.contains(v) == Set.of(xs).has(v))
assert(xs.contains(v) == xs.reverse().contains(v))
}After Array.push, the array contains the pushed value:
let xs = ["a", "b"]
xs.push("c")
assert(xs.contains("c"))Array.unique keeps the first of each == value. A loop that pushes only what the result does not yet contain builds the same array:
let xs = [2, 7, 2, 1, 7]
let ys: Array[int] = []
for v in xs {
if !ys.contains(v) {
ys.push(v)
}
}
assert(ys == xs.unique())Possible issues
NaN is not == to itself, so an array never contains it. Test with Math.isNaN:
let xs = [1.0, Math.NaN]
xs.contains(Math.NaN) // false
xs.some({ Math.isNaN(x) }) // true
[0.0].contains(-0.0) // trueNumeric types never mix, so looking for a float64 in an Array[int] is a compile error:
let counts = [1, 2, 3]
println(counts.contains(2.0)) // error: cannot use float64 where int is expectedNor is null a valid value unless the element type includes it:
let counts = [1, 2, 3]
println(counts.contains(null)) // error: cannot use null where int is expectedA nullable value, such as the result of Array.get, Map indexing, or Array.first, is not an int either, so it cannot be looked up in an Array[int] as it is:
let xs = [1, 2, 3]
let m: int | null = Map{ a: 2 }["a"]
println(xs.contains(m)) // error: cannot use int | null where int is expectedNarrow it first:
let xs = [1, 2, 3]
let m: int | null = Map{ a: 2 }["a"]
m != null && xs.contains(m) // trueArray.contains takes a value, not a predicate. To test elements with a function, use Array.some:
let counts = [1, 2, 3]
println(counts.contains({ x > 2 }))
// error: a lambda needs an expected function type, but int is expected== compares records by their contents at the time of the call. A record changed after it went into the array matches its new fields, and a copy matches as well as the original. To ask whether the array holds one particular record, compare identity with Record.same:
type Point = { x: int, y: int }
let p = Point{ x: 1, y: 2 }
let ps = [p]
p.x = 5
ps.contains(Point{ x: 1, y: 2 }) // false
ps.contains(Point{ x: 5, y: 2 }) // true
ps.some({ Record.same(x, Point{ ...p }) }) // false
ps.some({ Record.same(x, p) }) // trueFunctions compare by identity, so two lambdas with the same body are different values:
let inc: func(int): int = { x + 1 }
let same: func(int): int = { x + 1 }
[inc].contains(inc) // true
[inc].contains(same) // falseText that can arrive in either Unicode spelling needs normalizing on both sides first, with String.normalize:
let names = ["café"].map({ x.normalize("NFC") })
names.contains("cafe\u{301}".normalize("NFC")) // trueSee also
Array.indexOf · Array.lastIndexOf · Array.some · Array.find · Array.unique · Set.has · Map.has · String.contains · == operator
