Last active
September 29, 2021 00:34
-
-
Save OlivierBinette/a048d7c1f470740b64e95c74828c8516 to your computer and use it in GitHub Desktop.
[Assert] Validate function arguments #R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
assert <- function(..., msg=NULL) { | |
# Assert that each of the provided expression is true. Otherwise returns a | |
# description of each failed assertion. | |
# | |
# Args: | |
# ...: List of logical assertions | |
# msg: Optional parameter printed when one of the assertions fails. | |
# | |
# Returns: | |
# Nothing if all assertions pass. Otherwise throws an error describing which | |
# assertions failed. | |
# | |
# Examples: | |
# > assert(2 < 1, 1 == 1, "1" == 2) | |
# ## Error in assert(2 < 1, 1 == 1, "1" == 2) : Failed checks: | |
# ## 2 < 1 | |
# ## "1" == 2 | |
# | |
# # In a function to validate arguments: | |
# > sum <- function(a, b) { | |
# > assert(is.numeric(a), | |
# > is.numeric(b), | |
# > length(a) == length(b)) | |
# > return(a+b) | |
# > } | |
# > sum("1", 2) | |
# ## Error: in sum(a = "1", b = c(1, 2)) | |
# ## Failed checks: | |
# ## is.numeric(a) | |
# ## length(a) == length(b) | |
# | |
r = c(...) | |
if (any(!r)) { | |
fails = paste0(substitute(c(...)))[-1][!r] | |
if(identical(parent.frame(), globalenv())) { | |
stop(c("Failed checks: \n\t", | |
paste(fails, "\n\t"), | |
"\n", msg)) | |
} else { | |
msg = c("in ", | |
eval(quote(match.call()), parent.frame()), | |
"\n", | |
"Failed checks: \n\t", | |
paste(fails, "\n\t"), | |
"\n", msg) | |
stop(msg, call. = FALSE) | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sum <- function(a, b) { | |
assert(is.numeric(a), is.numeric(b)) | |
assert(length(a) == length(b)) | |
return(a+b) | |
} | |
sum("1", c(1,2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment