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

Comparisons in purrr #234

Closed
lionel- opened this issue Sep 1, 2016 · 4 comments
Closed

Comparisons in purrr #234

lionel- opened this issue Sep 1, 2016 · 4 comments

Comments

@lionel-
Copy link
Member

lionel- commented Sep 1, 2016

reduce_common <- function(x, msg = "Objects must be identical",
                          operator = identical) {
  reduce(x, function(.x, .y) {
    if (!operator(.x, .y)) {
      stop(msg, call. = FALSE)
    }
    .y
  })
}

reduce_common_lgl <- function(.x, operator = identical) {
  safe_reduce_common <- safely(reduce_common)
  reduced <- safe_reduce_common(.x, operator = operator)
  is.null(reduced$error)
}
#' Companion to identical()
equal <- function(x, y) {
  isTRUE(all.equal(x, y))
}

all_equal <- function(x) {
  reduce_common_lgl(x, operator = equal)
}
all_identical <- function(x) {
  reduce_common_lgl(x)
}
list(1, 1, 1.0001) %>% all_equal()
#> [1] FALSE

list(1, 1, 1.00000000001) %>% all_equal()
#> [1] TRUE

list(1, 1, 1.00000000001) %>% all_identical()
#> [1] FALSE
@lionel-
Copy link
Member Author

lionel- commented Sep 1, 2016

From a stylistic point of view, I'm not sure if it's better to use a functional + error throwing, rather than a for loop + break.

In the latter case we'd have the loop inside reduce_common_lgl() called by the user-facing reduce_common() which would throw an error on FALSE.

@lionel-
Copy link
Member Author

lionel- commented Sep 1, 2016

Maybe the stylistic rule should be that when we break the purity of (part of) a function we shouldn't apply a functional makeup on it. In that case the for loop is better (and more efficient).

@hadley
Copy link
Member

hadley commented Oct 3, 2016

Can you move that to vctrs?

@lionel-
Copy link
Member Author

lionel- commented Mar 7, 2017

Moved to rlang

@lionel- lionel- closed this as completed Mar 7, 2017
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

No branches or pull requests

2 participants