Skip to content

Implement some() and every() helpers#716

Merged
hadley merged 1 commit into
mainfrom
some-every
Jun 24, 2026
Merged

Implement some() and every() helpers#716
hadley merged 1 commit into
mainfrom
some-every

Conversation

@hadley

@hadley hadley commented Jun 24, 2026

Copy link
Copy Markdown
Member

These are more efficient than any/all plus vapply() because they can early exit. Benchmarking confirms that they are faster even in the worst case scenario (TRUE/FALSE at last entry).

x <- as.list(1:10)
bench::mark(
  # some() early-exits on first TRUE; any(vlapply) computes all
  some_early    = some(x, \(v) v > 0),
  any_vlapply   = any(vlapply(x, \(v) v > 0)),
  # worst case: no early exit possible
  every_full    = every(x, \(v) v > 0),
  all_vlapply   = all(vlapply(x, \(v) v > 0)),
  check = FALSE
)[1:4]

#>   expression       min   median `itr/sec`
#>   <bch:expr>  <bch:tm> <bch:tm>     <dbl>
#> 1 some_early  410.01ns 574.04ns  1157952.
#> 2 any_vlapply   2.38µs   2.91µs   313534.
#> 3 every_full    1.31µs   1.64µs   563264.
#> 4 all_vlapply   2.34µs   2.91µs   330469.

These are more efficient than `any`/`all` plus `vapply()` because they can early exit. Benchmarking confirms that they are faster even in the worst case scenario (`TRUE`/`FALSE` at last entry).

```R
x <- as.list(1:10)
bench::mark(
  # some() early-exits on first TRUE; any(vlapply) computes all
  some_early    = some(x, \(v) v > 0),
  any_vlapply   = any(vlapply(x, \(v) v > 0)),
  # worst case: no early exit possible
  every_full    = every(x, \(v) v > 0),
  all_vlapply   = all(vlapply(x, \(v) v > 0)),
  check = FALSE
)[1:4]

#>   expression       min   median `itr/sec`
#>   <bch:expr>  <bch:tm> <bch:tm>     <dbl>
#> 1 some_early  410.01ns 574.04ns  1157952.
#> 2 any_vlapply   2.38µs   2.91µs   313534.
#> 3 every_full    1.31µs   1.64µs   563264.
#> 4 all_vlapply   2.34µs   2.91µs   330469.
```
@hadley
hadley requested a review from t-kalinowski June 24, 2026 12:40
@hadley
hadley merged commit 4da2a3b into main Jun 24, 2026
13 checks passed
@hadley
hadley deleted the some-every branch June 24, 2026 13:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants