Skip to main content

22  Generics and methods

This part declares behavior in R style: a generic, and a method of it for each type. Traits and impls declares the same behavior in Rust style.

22.1 A generic and its method

generic(name, params) declares a generic, a function that calls the method for the R8 type of its first argument. params() gives its parameters, in order:

resample <- generic(
  "resample",
  params(x, n_cases),
  description = "Draws the training sets of n_cases cases."
)

implement(generic, Type) <- function(...) declares the method for a type, with the generic’s parameters. The method for an enum covers every variant, here with a switch() on the variant’s name. A value has the fields of its variant only, so the method reads train_p for StratSub alone:

implement(resample, Resampler) <- function(x, n_cases) {
  if (!is.null(x$seed)) set.seed(x$seed)
  n <- x$n_resamples
  train <- switch(
    r8variant(x),
    KFold = {
      fold <- sample(rep_len(seq_len(n), n_cases))
      lapply(seq_len(n), function(k) which(fold != k))
    },
    StratSub = replicate(
      n,
      sort(sample.int(n_cases, round(x$train_p * n_cases))),
      simplify = FALSE
    ),
    Bootstrap = replicate(
      n,
      sort(sample.int(n_cases, replace = TRUE)),
      simplify = FALSE
    ),
    stop("unsupported resampler: ", r8variant(x))
  )
  Resamples(resampler = x, n_cases = n_cases, train = train)
}

The generic is called as any function:

draws <- resample(cv, n_cases = 20L)
lengths(draws$train)
 [1] 18 18 18 18 18 18 18 18 18 18
boot <- resample(Resampler@Bootstrap(n_resamples = 3L), n_cases = 5L)
length(boot$train)
[1] 3

Printing it shows its qualified name, its parameters, and the types with a method:

resample
<r8 generic demo::resample>
resample(x, n_cases)
Methods for: demo::Resampler

22.2 Dispatch

A type without a method is an error that names the type and the generic:

resample(draws, n_cases = 20L)
Error:
! `demo::Resamples` does not implement `demo::resample` (method `resample`).

A struct that extends another takes its parent’s methods (Extending a struct).

r8method(generic, Type) returns the method itself, for tests that call it without dispatch:

method <- r8method(resample, Resampler)
lengths(method(cv, n_cases = 10L)$train)
 [1] 9 9 9 9 9 9 9 9 9 9

22.3 Parameters

A method has exactly the generic’s parameters, and a call with another argument is an error:

implement(resample, Resampler) <- function(x, n) NULL
Error:
! The method of `resample` takes exactly the generic's parameters: function(x, n_cases).
resample(cv, n_cases = 20L, stratify = TRUE)
Error in `resample()`:
! unused argument (stratify = TRUE)

A generic declared with "..." lets each method add parameters of its own after it:

label <- generic("label", params(x, "..."))

implement(label, Resampler) <- function(x, ..., upper = FALSE) {
  variant <- r8variant(x)
  if (upper) toupper(variant) else variant
}

label(cv, upper = TRUE)
[1] "KFOLD"

params() reads its arguments without evaluating them. A bare name is a parameter without a default, name = expression one with a default, and "..." is written as a string. A default belongs to the generic. It is evaluated at each call that omits the argument, where the other parameters are visible, and then where params() is called, so it may call a function that a package does not export:

default_workers <- function() 2L

tasks_per_worker <- generic(
  "tasks_per_worker",
  params(x, n_tasks = x$n_resamples, n_workers = default_workers())
)

implement(tasks_per_worker, Resampler) <- function(x, n_tasks, n_workers) {
  ceiling(n_tasks / n_workers)
}

tasks_per_worker(cv)
[1] 5
tasks_per_worker(cv, n_workers = 4L)
[1] 3

A method gives no default to a parameter of its generic:

implement(tasks_per_worker, Resampler) <- function(x, n_tasks, n_workers = 1L) {
  ceiling(n_tasks / n_workers)
}
Error:
! The method of `tasks_per_worker` gives `n_workers` a default, which belongs to the generic: `n_workers = 1L` in its params() [method_default].

Parameters may also have types (Typed arguments and results).

22.4 Dispatch on several arguments

dispatch names the arguments a generic dispatches on, the first by default. A method gives a type for any of them, by position or by name, and a position it does not name matches any value:

Grid <- new_struct("Grid", fields = list(step = type_double(exclusive_min = 0)))

snap <- generic("snap", params(x, grid), dispatch = c("x", "grid"))

implement(snap, Interval, Grid) <- function(x, grid) {
  Interval(
    lo = floor(x$lo / grid$step) * grid$step,
    hi = ceiling(x$hi / grid$step) * grid$step
  )
}

implement(snap, grid = Grid) <- function(x, grid) {
  round(x / grid$step) * grid$step
}

snap(Interval(lo = 0.3, hi = 1.6), Grid(step = 0.5))
<demo::Interval>
  lo: 0
  hi: 2
snap(c(0.3, 1.6), Grid(step = 0.5))
[1] 0.5 1.5

The method that is at least as specific as every other in every position runs. A child is more specific than its parent, and any is the least specific. Two methods that are each more specific in one position make a call on both ambiguous:

FineGrid <- new_struct("FineGrid", fields = list(digits = type_integer()), extends = Grid)
Padded <- new_struct("Padded", fields = list(pad = type_double()), extends = Interval)

implement(snap, Interval, FineGrid) <- function(x, grid) x
implement(snap, Padded, Grid) <- function(x, grid) x
snap(Padded(lo = 0, hi = 1, pad = 0.1), FineGrid(step = 0.5, digits = 2L))
Error:
! The call of `demo::snap` (method `snap`) on (demo::Padded, demo::FineGrid) is ambiguous: the impls for (demo::Interval, demo::FineGrid) and for (demo::Padded, demo::Grid) are each more specific in one position; implement it for (demo::Padded, demo::FineGrid) [dispatch_ambiguous].

r8ambiguities(snap) lists such pairs, for a package’s tests, and a package whose methods leave a call ambiguous with those of the packages it imports is refused when it loads. The generic evaluates exactly the arguments it dispatches on, whatever methods other packages declare. Inside a method, r8next_impl() continues to the next less specific method; when two are next, r8next_impl(Interval, Grid) names the one.

22.5 Replacement generics

A generic whose name ends in <- is a replacement generic, called as f(x) <- value. Its last parameter is value, and a method returns a value of the type of x:

`n_resamples<-` <- generic("n_resamples<-", params(x, value))

implement(`n_resamples<-`, Resampler) <- function(x, value) {
  x$n_resamples <- value
  x
}

short <- cv
n_resamples(short) <- 3L
c(cv$n_resamples, short$n_resamples)
[1] 10  3

A method that returns another type is an error:

implement(`n_resamples<-`, Resampler) <- function(x, value) value
n_resamples(short) <- 4L
Error:
! The replacement generic `demo::n_resamples<-`, from the method for `demo::Resampler`, returned an object of class "integer" for a value of `demo::Resampler`; a replacement method returns a value of its argument's type, such as x after `x$field <- value` [replacement_type].

Its trait is demo::with_n_resamples, which names the method in the bindings other than R.

22.6 Names

A generic is assigned to a name, which a package exports and documents as it does a function. generic() declares a trait of one method in the namespace, demo::resample; types, traits, and generics share one set of names per namespace. A generic’s name is not the name of a function of base R or of the package’s imports; for those, implement() declares a method directly (Methods of base generics):

generic("summary", params(object))
Error:
! `summary` is a generic of 'base'; declare its method for a type with implement(summary, Type) <- function(object, ...) ...
© 2026 E.D. Gennatas