Skip to content

Instantly share code, notes, and snippets.

@moodymudskipper
Last active October 14, 2020 13:55
Show Gist options
  • Save moodymudskipper/db3683974aee3e9b8ecb40f029327f59 to your computer and use it in GitHub Desktop.
Save moodymudskipper/db3683974aee3e9b8ecb40f029327f59 to your computer and use it in GitHub Desktop.
typed
options(typed.typed = TRUE)
`%typed%` <- function(e1, e2) {
if(getOption("typed.typed")) {
assert_call <- substitute(e1)
assert_call[[1]] <- quote(assertthat::assert_that)
eval.parent(assert_call)
}
e2
}
types <- function(f) {
b <- body(f)
if(is.call(b) && identical(b[[1]], quote(`%typed%`)))
return(as.list(b[[2]])[-1])
NULL
}
prefix <- function(str, len) {
is.character(str)
is.integer(len)
} %typed% {
substring(str, 1, len)
}
types(prefix)
#> [[1]]
#> is.character(str)
#>
#> [[2]]
#> is.integer(len)
prefix(42, 1)
#> Error: str is not a character vector
prefix("test", 1)
#> Error: len is not an integer vector
prefix("test", 1L)
#> [1] "t"
options(typed.typed = FALSE)
prefix(42, 1)
#> [1] "4"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment