Skip to main content

19  Typed functions

A typed function declares the types of its parameters and of its result. Each call checks and converts its arguments before the body runs, and checks the result before it is returned. The declaration has a name in the package’s namespace, as a type does, so that the function’s parameters, their types, and their rules are known beyond the function’s code: in its documentation, to other languages, and to a program that writes a call.

19.1 A function and its types

new_function(name, fn) declares the function fn. The types are in its formals: arg(type, default) gives a parameter a type, and each type constructor has a shorthand, arg_double(min = 0) for arg(type_double(min = 0)):

clip <- new_function(
  "clip",
  function(x = arg_vec(type_double()), lo = arg_double(), hi = arg_double(default = 1)) {
    pmin(pmax(x, lo), hi)
  },
  return_type = vec(type_double())
)
clip(c(-1, 0.5, 3), lo = 0L)
[1] 0.0 0.5 1.0
clip
<r8 function demo::clip>
clip(x, lo, hi)
  x: vector of double
  lo: double
  hi: double = 1
  returns vector of double

lo = 0L is an integer, and the function receives the double 0, as a constructor converts it. A parameter without a default is required. An argument that does not satisfy its type is an error, which lists every problem of the call:

clip("a", lo = "b")
Error:
! Invalid arguments of `clip()`: 2 problems
- `x` must be a numeric vector; found a character vector. [r_type]
- `lo` must be a numeric vector; found a character vector. [r_type]

The function given to new_function() is plain R: called without R8, arg() gives its default and checks nothing.

19.2 Rules over parameters

rules hold over the typed parameters, which a rule reads by name, as a struct’s rules read its fields. They are checked once every argument satisfies its type:

span <- new_function(
  "span",
  function(lo = arg_double(), hi = arg_double()) hi - lo,
  rules = list(order = rule(lo <= hi, message = "lo is at most hi."))
)
span(1, 3)
[1] 2
span(3, 1)
Error:
! Invalid arguments of `span()`: 1 problem
- Rule order: lo is at most hi. [rule_violation]
  lo <= hi; found lo = 3, hi = 1

19.3 The function’s own frame

The body runs in the function’s own frame, after the check. substitute(), match.call(), sys.call(), parent.frame(), missing(), and on.exit() mean what they mean in a plain function, so that an existing function becomes typed without a change of its body:

summarize_column <- new_function(
  "summarize_column",
  function(data = arg(host_class("data.frame")), column = arg_character(), ...) {
    list(data = deparse(substitute(data)), call = match.call())
  }
)
visits <- data.frame(age = c(40, 52))
summarize_column(visits, "age")
$data
[1] "visits"

$call
summarize_column(data = visits, column = "age")

With return_type, each return() of the body and its last value are checked; an invisible result stays invisible.

19.4 An existing function

An existing function becomes typed by its formals alone. Its defaults move into arg(), and its body, which runs in the same frame as before, stays as it is:

random_matrix <- function(nrow = 10, ncol = 10, mean = 0, sd = 1, seed = NULL) {
  if (!is.null(seed)) set.seed(seed)
  matrix(stats::rnorm(nrow * ncol, mean, sd), nrow, ncol)
}
random_matrix <- new_function(
  "random_matrix",
  function(
    nrow = arg_integer(min = 0L, default = 10L),
    ncol = arg_integer(min = 1L, default = 10L),
    mean = arg_double(default = 0),
    sd = arg_double(min = 0, default = 1),
    seed = arg_option(type_integer())
  ) {
    if (!is.null(seed)) set.seed(seed)
    matrix(stats::rnorm(nrow * ncol, mean, sd), nrow, ncol)
  }
)
dim(random_matrix(3, 2, seed = 1))
[1] 3 2
random_matrix(-1, 2.5, sd = -1)
Error:
! Invalid arguments of `random_matrix()`: 3 problems
- `nrow` must be at least 0; found -1. [below_min]
- `ncol` must be a whole number from -2147483647 to 2147483647; found 2.5. [r_type]
- `sd` must be at least 0; found -1. [below_min]

The checks that a body wrote by hand, such as a test that two factors have the same levels, become rules, rule(levels(true_labels) == levels(predicted_labels)), and leave the body. A parameter has one type: an argument that may be a vector or a matrix, and a result that is a matrix or a data frame by a flag, are two functions.

19.5 Parameters without types

A parameter may have no type, and the function may take ...: a call checks the parameters that have types. typed = "strict" asks a type of every parameter, and refuses ...:

new_function("weigh", function(x, w = arg_double()) x * w, typed = "strict")
Error:
! Declaration of `demo::weigh` failed:
- parameter `x` of the strictly typed function `weigh` has no type [untyped_param at /params/0]

A function whose parameters all have types is described completely, to a program or to another language (Calls from documents).

19.6 Cost

The table gives the time that the checks add to a call, in nanoseconds (bench/typed.R in the R8 repository; R 4.6.2, Apple M5, 2026-11-25, and 2026-11-26 for the vector; minimum of 7 rounds). A rule over two parameters adds about 115 ns:

Check new_function() Hand-written checkmate 2.3.4
An integer and a double 261 453 1,441 (qassert())
A struct 259 123 (inherits()) 3,815 (assert_class())
A result, one double 116 163 1,036 (assert_number())
An integer, a double, and a rule 360
10^6 doubles of at least 0 275,000 2,180,000 708,000 (assert_numeric())

A function whose time is in its body, in R’s loops or temporary vectors, can keep its declaration and move its body to Rust (Moving a function to Rust).

© 2026 E.D. Gennatas