-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathevery-some-none.R
More file actions
69 lines (62 loc) · 2.03 KB
/
every-some-none.R
File metadata and controls
69 lines (62 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#' Do every, some, or none of the elements of a list satisfy a predicate?
#'
#' * `some()` returns `TRUE` when `.p` is `TRUE` for at least one element.
#' * `every()` returns `TRUE` when `.p` is `TRUE` for all elements.
#' * `none()` returns `TRUE` when `.p` is `FALSE` for all elements.
#'
#' @inheritParams keep
#' @param ... Additional arguments passed on to `.p`.
#' @return A logical vector of length 1.
#' @export
#' @examples
#' x <- list(0:10, 5.5)
#' x |> every(is.numeric)
#' x |> every(is.integer)
#' x |> some(is.integer)
#' x |> none(is.character)
#'
#' # Missing values are propagated:
#' some(list(NA, FALSE), identity)
#'
#' # If you need to use these functions in a context where missing values are
#' # unsafe (e.g. in `if ()` conditions), make sure to use safe predicates:
#' if (some(list(NA, FALSE), rlang::is_true)) "foo" else "bar"
every <- function(.x, .p, ...) {
satisfies_predicate(.x, .p, ..., .purrr_predicate = "every")
}
#' @export
#' @rdname every
some <- function(.x, .p, ...) {
satisfies_predicate(.x, .p, ..., .purrr_predicate = "some")
}
#' @export
#' @rdname every
none <- function(.x, .p, ...) {
satisfies_predicate(.x, .p, ..., .purrr_predicate = "none")
}
satisfies_predicate <- function(
.x,
.p,
...,
.purrr_predicate,
.purrr_user_env = caller_env(2),
.purrr_error_call = caller_env()
) {
# Not using `as_predicate()` as R level predicate result checks are too slow.
# Checks are done at the C level instead (#1169). Also, `NA` propagates
# through these functions, which `as_predicate()` doesn't allow.
.p <- as_mapper(.p, ...)
# Consistent with `map()`
.x <- vctrs_vec_compat(.x, .purrr_user_env)
obj_check_vector(.x, arg = ".x", call = .purrr_error_call)
n <- vec_size(.x)
i <- 0L
# We refer to `.p`, `.x`, `i`, `...`, and `.purrr_error_call` all from C level
switch(
.purrr_predicate,
every = .Call(every_impl, environment(), n, i),
some = .Call(some_impl, environment(), n, i),
none = .Call(none_impl, environment(), n, i),
abort("Unreachable", .internal = TRUE)
)
}