# returns TRUE if x is a positive, integer, FALSE otherwise
# if invoked as part of an assertion displays a custom failure diagnosis
is_positive_int <- function(x) {
is.integer(x) && length(x) == 1L && (x > 0) || {
diagnose_assertion_failure(
sprintf("`%s` must be a positive integer", forwarded_arg_label(x)),
{{x}}
)
}
}
# for all intends and purposes this is just a regular R function that returns
# TRUE or FALSE
is_positive_int(5L)
is_positive_int(-5L)
# guard to avoid throwing errors
if(FALSE) {
# ... but it will provide custom diagnosis if invoked inside an assertion
precondition(is_positive_int(-5L))
}
Run the code above in your browser using DataLab