Array.some
func Array.some[T](xs: Array[T], f: func(T): bool): boolArray.some reports whether f accepts at least one element of xs.
Details
- Returns
falseon an empty array. - Calls
ffrom the first element and stops at the first onefaccepts.
Basic examples
Array.some([1, 3, 4], { x % 2 == 0 }) // true
Array.some([1, 3, 5], { x % 2 == 0 }) // falseCall it through . on any array:
let temps = [18, 24, 31]
temps.some({ x > 30 }) // true
temps.some({ x < 0 }) // falseThe callback runs from the first element and stops at the first element it accepts, so a side effect shows which elements it tested:
let seen: Array[int] = []
[1, 3, 4, 5, 6].some({ seen.push(x); x % 2 == 0 }) // true
seen // [1, 3, 4]When f accepts no element, it tests them all:
let seen: Array[int] = []
[1, 3, 5].some({ seen.push(x); x % 2 == 0 }) // false
seen // [1, 3, 5]Scope
Pass a declared function by name instead of a lambda:
func isNegative(n: int): bool {
n < 0
}
[3, -1, 4].some(isNegative) // true
[3, 1, 4].some(isNegative) // falseLibrary functions are values too. String.isEmpty finds a blank entry:
["Ann", "", "Bob"].some(String.isEmpty) // true
["Ann", "Bob"].some(String.isEmpty) // falseStrings compare by their text, Unicode included:
["mañana", "Ωμέγα", "🐜"].some({ x == "🐜" }) // true
["mañana", "Ωμέγα"].some({ x.startsWith("Ω") }) // trueRecords are read through their fields:
type Order = { id: int, paid: bool }
let orders = [Order{ id: 1, paid: true }, Order{ id: 2, paid: false }]
orders.some({ !x.paid }) // true
orders.some({ x.id > 10 }) // falseWith a union, test the tag with is. Inside &&, x is narrowed to the member:
type Circle = { radius: float64 }
type Rect = { width: float64, height: float64 }
type Shape = Circle | Rect
let shapes: Array[Shape] = [Circle{ radius: 1.0 }, Rect{ width: 2.0, height: 3.0 }]
shapes.some({ x is Rect }) // true
shapes.some({ x is Circle && x.radius > 2.0 }) // falseAn element type that includes null can be searched for null itself, or for a value once null is ruled out:
let scores: Array[int | null] = [90, null, 75]
scores.some({ x == null }) // true
scores.some({ x != null && x > 80 }) // true
scores.some({ x != null && x > 95 }) // falseFor nested arrays, each nested lambda binds its own x:
let grid = [[0, 0], [0, 7]]
grid.some({ x.some({ x != 0 }) }) // true
grid.some({ x.isEmpty() }) // falseThe values of a map or the members of a set are arrays through Map.values and Set.values:
let stock = Map{ apples: 4, pears: 0 }
stock.values().some({ x == 0 }) // true
Set.of([2, 4, 6]).values().some({ x % 2 == 1 }) // falseIn a pipeline, the array is the first argument:
"red green blue" | String.split(" ") | Array.some({ x.length() > 4 }) // trueA closure sees later assignments to the variables it captures:
var target = 3
let hit: func(int): bool = { x == target }
[1, 2, 3].some(hit) // true
target = 9
[1, 2, 3].some(hit) // falseApplications
Check a password for at least one digit:
func hasDigit(s: string): bool {
s.chars().some({ x.isDigit() })
}
hasDigit("hunter2") // true
hasDigit("hunter") // falseRefuse a deploy when any check failed:
type Check = { name: string, ok: bool }
func deploy(checks: Array[Check]): Result[void, string] {
if checks.some({ !x.ok }) {
let failed = checks.filter({ !x.ok }).map({ x.name })
Result.err("failed: ${String.join(failed, ", ")}")
} else {
Result.ok(void)
}
}
println(deploy([Check{ name: "test", ok: true }, Check{ name: "lint", ok: true }]))
println(deploy([Check{ name: "test", ok: false }, Check{ name: "lint", ok: true }]))Ok{ value: void }
Err{ error: "failed: test" }Find whether an array has a duplicate, by comparing each index with the first index of its value:
func hasDuplicate(xs: Array[string]): bool {
Array.range(0, xs.length()).some({ xs.indexOf(xs[x]) != x })
}
hasDuplicate(["a", "b", "a"]) // true
hasDuplicate(["a", "b", "c"]) // falseCheck whether an array shares an element with a set:
let mine = Set.of(["go", "ant", "zig"])
["rust", "ant"].some({ mine.has(x) }) // true
["c", "lua"].some({ mine.has(x) }) // falseSince the call stops at the first match, an expensive test runs only as far as it must. Here the lookup runs until a cached key is found:
let cache = Map{ a: 1, c: 3 }
var lookups = 0
let cached: func(string): bool = {
lookups += 1
cache.has(x)
}
["b", "c", "a", "d"].some(cached) // true
lookups // 2Properties and relations
Array.some is true exactly when Array.every fails for the opposite test, when Array.findIndex finds an index, and when Array.countWhere and Array.filter keep at least one element:
let f: func(int): bool = { x % 3 == 0 }
for xs in [[1, 2, 4], [1, 3, 4], []] {
assert(xs.some(f) == !xs.every({ !f(x) }))
assert(xs.some(f) == (xs.findIndex(f) != null))
assert(xs.some(f) == (xs.countWhere(f) > 0))
assert(xs.some(f) == !xs.filter(f).isEmpty())
}Testing for a value with == is what Array.contains does:
let xs = ["a", "b", "c"]
assert(xs.some({ x == "b" }) == xs.contains("b"))
assert(xs.some({ x == "z" }) == xs.contains("z"))Over a concatenation, some holds when it holds on either part:
let f: func(int): bool = { x < 0 }
let xs = [1, 2]
let ys = [3, -4]
assert(xs.concat(ys).some(f) == (xs.some(f) || ys.some(f)))
assert(!xs.some(f) && ys.some(f))Possible issues
An empty array gives false for some, even for a test that accepts everything, while every gives true, even for a test that rejects everything:
let errors: Array[string] = []
errors.some({ true }) // false
errors.every({ false }) // truef must return a bool. Ant has no truthy values, so a lambda that returns an int is a compile error:
let counts = [0, 1, 2]
println(counts.some({ x })) // error: cannot use int where bool is expectedWrite the comparison instead:
[0, 1, 2].some({ x != 0 }) // trueArray.some takes a predicate, not a value. Passing the value itself is a compile error; use Array.contains to test by ==:
let xs = [1, 2, 3]
println(xs.some(2)) // error: cannot use int where func(int): bool is expected[1, 2, 3].contains(2) // trueA lambda stored in an unannotated let has no expected function type. Annotate the variable:
let big = { x > 100 }
// error: a lambda needs an expected function type; annotate the variable or use func with typed parameters
println([1, 200].some(big))The call reads the elements once, when it is called. A callback that pushes to the array changes it, but not which elements some visits, unlike a for loop, which reads its collection as it goes:
let xs = [1, 2]
xs.some({ xs.push(9); x == 9 }) // false
xs // [1, 2, 9, 9]NaN is not == to any value, itself included, because floats compare by IEEE 754 rules, so x == Math.NaN never finds it. Test for it with Math.isNaN:
let xs = [1.0, Math.NaN]
xs.some({ x == Math.NaN }) // false
xs.some({ Math.isNaN(x) }) // trueSee also
Array.every · Array.find · Array.findIndex · Array.filter · Array.countWhere · Array.contains · Set.has
