input-validators | R Documentation |
localize
derives a function that generates check formulae of
local scope from a check formula of global scope. globalize
takes such
a check-formula generator and returns the underlying global check formula.
These operations are mutually invertible.
localize(chk)
globalize(chkr)
chk |
Check formula of global scope with custom error message,
i.e., a formula of the form |
chkr |
Function of class |
localize
returns a function of class "check_maker"
and
call signature function(...)
:
The ...
are check items (see Check Formulae
of Local Scope in the documentation page firmly).
The return value is the check formula of local scope whose scope is
comprised of these check items, and whose predicate function is that of
chk
(i.e., the right-hand side of chk
). Unless a check
item has its own error message, the error message is derived from that
of chk
(i.e., the left-hand side of chk
).
globalize
returns the global-scope check formula from which
the function chkr
is derived.
The notion of “scope” is explained in the Check Formulae section of firmly.
Ready-made checkers for types, scalar objects, and miscellaneous predicates are provided as a convenience, and as a model for creating families of check makers.
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
## Not run:
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)"
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.