chk_pos_gbl <- "Not positive" ~ {. > 0}
chk_pos_lcl <- localize(chk_pos_gbl)
chk_pos_lcl(~x, "y not greater than x" ~ x - y)
# list("Not positive: x" ~ x, "y not greater than x" ~ x - y) ~ {. > 0}
# localize and globalize are mutual inverses
identical(globalize(localize(chk_pos_gbl)), chk_pos_gbl) # [1] TRUE
all.equal(localize(globalize(chk_pos_lcl)), chk_pos_lcl) # [1] TRUE
if (FALSE) {
pass <- function(x, y) "Pass"
# Impose local positivity checks
f <- firmly(pass, chk_pos_lcl(~x, "y not greater than x" ~ x - y))
f(2, 1) # [1] "Pass"
f(2, 2) # Error: "y not greater than x"
f(0, 1) # Errors: "Not positive: x", "y not greater than x"
# Or just check positivity of x
g <- firmly(pass, chk_pos_lcl(~x))
g(1, 0) # [1] "Pass"
g(0, 0) # Error: "Not positive: x"
# In contrast, chk_pos_gbl checks positivity for all arguments
h <- firmly(pass, chk_pos_gbl)
h(2, 2) # [1] "Pass"
h(1, 0) # Error: "Not positive: `y`"
h(0, 0) # Errors: "Not positive: `x`", "Not positive: `y`"
# Alternatively, globalize the localized checker
h2 <- firmly(pass, globalize(chk_pos_lcl))
all.equal(h, h2) # [1] TRUE
# Use localize to make parameterized checkers
chk_lte <- function(n, ...) {
err_msg <- paste("Not <=", as.character(n))
localize(err_msg ~ {. <= n})(...)
}
fib <- function(n) {
if (n <= 1L) return(1L)
Recall(n - 1) + Recall(n - 2)
}
capped_fib <- firmly(fib, chk_lte(30, ~ ceiling(n)))
capped_fib(19) # [1] 6765
capped_fib(31) # Error: "Not <= 30: ceiling(n)"
}
Run the code above in your browser using DataLab