Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

detect() predicate #383

Closed
lionel- opened this issue Sep 8, 2017 · 3 comments
Closed

detect() predicate #383

lionel- opened this issue Sep 8, 2017 · 3 comments
Labels
feature a feature request or enhancement map 🗺️

Comments

@lionel-
Copy link
Member

lionel- commented Sep 8, 2017

Parameterise detect() with a predicate:

detect <- function(.x, .f, ..., .right = FALSE, .p = is_true) {
  for (i in index(.x, .right)) {
    if (.p(.f(.x[[i]], ...))) {
      return(.x[[i]])
    }
  }
  NULL
}

Useful for detecting non-null values for instance.

@lionel-
Copy link
Member Author

lionel- commented Sep 8, 2017

Along with something like:

detect_value <- function(.x, .f, .p, ..., .right = FALSE) {
  for (i in index(.x, .right)) {
    value <- .f(.x[[i]], ...)
    if (.p(value)) {
      return(value)
    }
  }
  NULL
}

detect_value(x, some_fn, negate(is_null))

@hadley hadley added the feature a feature request or enhancement label Feb 5, 2018
@lionel-
Copy link
Member Author

lionel- commented Nov 16, 2018

Or should we test with is_trueish() instead?

is_trueish <- function(x) {
  if (is_true(x)) {
    return(TRUE)
  }
  if (is_integerish(x, n = 1L, finite = TRUE)) {
    return(x != 0)
  }
  FALSE
}

Then we can use it with e.g. anyDuplicated()

  detect(list(1:3, 4:6, c(7L, 8L, 7L)), anyDuplicated)
  #> [1] 7 8 7

Or should we keep is_true() by default, parameterise .p, and add is_trueish() to rlang?

@lionel- lionel- added the advice label Nov 22, 2018
@lionel- lionel- removed the advice label Nov 30, 2018
@lionel-
Copy link
Member Author

lionel- commented Nov 30, 2018

Would get in the way of #470, and can be solved by wrapping .f with .p manually.

@lionel- lionel- closed this as completed Nov 30, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature a feature request or enhancement map 🗺️
Projects
None yet
Development

No branches or pull requests

2 participants