input-validators {valaddin}R Documentation

Generate input-validation checks

Description

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.

Usage

localize(chk)

globalize(chkr)

Arguments

chk

Check formula of global scope with custom error message, i.e., a formula of the form <string> ~ <predicate>.

chkr

Function of class "check_maker", i.e., a function created by localize.

Value

localize returns a function of class "check_maker" and call signature function(...):

globalize returns the global-scope check formula from which the function chkr is derived.

See Also

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.

Examples

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)


[Package valaddin version 1.0.2 Index]