contractr adds run-time type contracts to R functions. You annotate a
function with a type declaration; contractr injects assertions that check the
arguments and the return value against that type every time the function is
called, warning (or erroring, depending on the configured severity) whenever a
value does not conform.
Types are written in the tastr type-declaration language.
contractr is published on the PRL-PRG r-universe:
install.packages("contractr", repos = "https://prl-prg.r-universe.dev")To install from source you need a C++17 compiler. The tastr type library is bundled as a git submodule and built automatically at install time, so clone recursively:
git clone --recurse-submodules https://github.com/PRL-PRG/contractr
R CMD INSTALL contractrlibrary(contractr)
greet <- function(name) paste("hi", name)
# require a double argument and a character result
insert_contract(greet, "<double> => character")
greet(42) # ok
greet("bob") # contract violation: parameter 'name' expected double, actual characterYou can also check or infer a value's type directly:
check_type(2L, "double") # TRUE
infer_type(c(1.0, 2.0)) # "double[]"