egnha / valaddin

Functional input validation to make R functions more readable and robust
Other
33 stars 1 forks source link

String interpolation for error messages #16

Closed egnha closed 7 years ago

egnha commented 7 years ago

Fixed strings are used to specify custom error messages for check items, e.g., "x is not a scalar" ~ x. However, an equally simple yet more flexible error-message mechanism is possible using string interpolation, cf. Python PEP 498, the glue package, the str_interp() function from the stringr package.

For example, a check item like

"((.)) is not a scalar (its length is {length(.)})" ~ x

ought to produce the error message

"x is not a scalar (its length is 3)"

if x were a vector of length 3. (Would be nice to be able to use {{.}} rather than ((.)) to do deparse(substitute(.)), but that is already interpreted as a literal symbol, in glue.)

egnha commented 7 years ago

A good option for a literal symbol would indeed be {{.}}, if we make two passes with glue(): first to substitute values, then to substitute symbols. For example:

glue(glue("The value of length({{.}}) is {.}, not 1", . = "3"), . = "a")
## The value of length(a) is 3, not 1
egnha commented 7 years ago

Implemented in the quosures branch.