Skip to content

Instantly share code, notes, and snippets.

@egnha
Last active April 27, 2018 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egnha/52add617de38bb5b5bcd8751ff179140 to your computer and use it in GitHub Desktop.
Save egnha/52add617de38bb5b5bcd8751ff179140 to your computer and use it in GitHub Desktop.
Declarative post conditions
`%?%` <- function(value, predicate) {
list(value = value, predicate = predicate(value))
}
# Implicitly, `assert` is either a boolean or a value-predicate pair
`%because%` <- function(assert, reason) {
if (is.logical(assert)) {
if (!assert) stop(reason, call. = FALSE)
return(invisible(TRUE))
}
if (!assert$predicate) stop(reason, call. = FALSE)
invisible(assert$value)
}
# Simple assertion (returns TRUE, invisibly)
is.function(identity) %because% "`identity` should be a function"
# Verify and assign
f <- identity %?% is.function %because% "`f` must be a function"
stopifnot(identical(f, identity))
# Error: `f` must be a function
f <- NULL %?% is.function %because% "`f` must be a function"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment