type_check: Add type checks to annotated code

Description Usage Arguments Value Examples

Description

This function adds type checking to code annotated with types.

Usage

1
type_check(x, where = c("arguments", "body", "return"))

Arguments

x

The function or expression to be modified

where

The location to add type checks in a function, defaults to adding them everywhere (if annotations exist).

Value

The modified code, if the input is a function the returned object has class ‘checked_function’ and the print method print the original function definition rather than the modified code. If you would like to inspect the modified code use body(x).

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
library(types)
type.unary <- type_define(
  check = function(x) length(x) == 1,
  error = function(n, v, t) sprintf("`%s` has length `%s`, not `1`", n, length(v)))
type.numeric <- type_define( check = function(x) is.numeric(x))
type.equals_one <- type_define(
  check = function(x) x == 1,
  error = function(n, v, t) sprintf("`%s` equals `%s`, not `1`", n, deparse(v)))
f <- function(blah = ? unary) { blah ? numeric } ? equals_one
ff <- type_check(f)

ff(1)
## Not run: 
 ff(1:2) # `blah` has length `2`, not `1`
 ff("txt") # `blah` is a `character` not a `numeric`
 ff(2) # `f1\\(\\)` equals `2`, not `1`

## End(Not run)

jimhester/typeCheck documentation built on May 19, 2019, 10:34 a.m.