Description Usage Arguments Examples
Declare type of a function
1 |
f |
A function; the function to which type-annotations are added. |
signature |
A named list of character vector. The type / classes. Union class is supported, e.g. list(arg_1 = c("numeric", "matrix")) is allowed. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | ## Not run:
# Example 1
add_one <- function(x) { x + 1 }
add_one <- declare::type_ls(add_one, list(x = "numeric"))
add_one(10) # Runs fine
add_one(nrow(1:10)) # Expect type error since nrow of a vector returns NULL.
# Example 2
cbind_rows <- function(r1, r2) { cbind(r1, r2) }
cbind_rows <- declare::type_ls(cbind_rows, list(r1 = "matrix", r2 = "matrix"))
X <- matrix(1:9, 3, 3)
Y <- matrix(1:3, ncol = 3)
cbind_rows(Y, Y) # Runs fine
cbind_rows(X[1,], Y) # Expect type error since X[1,] is converted to vector implicitly.
# Example 3 - Partial specification
f <- function(x, y) { x[1:3, ] * y }
f <- declare::type_ls(f, list(y = "numeric")) # 'x' is unspecified
x <- matrix(1:9, 3, 3)
x2 <- as.data.frame(x)
k <- 5
f(x, k) # runs fine
f(x2, k) # runs fine
f(x2, "A") # type error
# Example 4 - Multiple labels
f <- function(x, y) { x[1:3, ] * y }
f <- declare::type_ls(f, list(x = c("matrix", "data.frame"), y = "numeric"))
x <- matrix(1:9, 3, 3)
x2 <- as.data.frame(x)
k <- 5
f(x, k) # runs fine
f(x2, k) # runs fine
f("A", k) # type error
## End(Not run)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.