Skip to main content

28  Traits and impls

This part declares behavior in Rust style: a trait, which groups methods under one name, and an impl of it for each type. Generics and methods declares the same behavior in R style.

28.1 A trait

new_trait() declares behavior that types implement: one or more methods under one name. trait_method() declares a method with its parameters (Generics and methods) and, when they are declared, their types and its return type (Typed arguments and results). default_impl is the method of a type that gives none:

Resample <- new_trait(
  "Resample",
  description = "Draws resamples.",
  methods = list(
    resample = trait_method(
      params(x, n_cases),
      description = "Draws the training sets of n_cases cases."
    ),
    n_resamples = trait_method(
      params(x),
      description = "The number of resamples.",
      default_impl = function(x) x$n_resamples
    )
  )
)

@ gives a method’s generic, which a package assigns to a name and exports:

resample <- Resample@resample
n_resamples <- Resample@n_resamples

28.2 An impl

impl() implements the trait for a type, with a function for each method. The impl for Resampler gives resample() and takes the default of n_resamples(). The method for an enum covers every variant, here with a switch() on the variant’s name:

impl(
  Resample,
  Resampler,
  methods = list(
    resample = 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)
    }
  )
)
draws <- resample(cv, n_cases = 20L)
lengths(draws$train)
 [1] 18 18 18 18 18 18 18 18 18 18
n_resamples(cv)
[1] 10

28.3 Dispatch

A trait’s generic dispatches on the R8 type of its first argument, or of the arguments its methods name (below). A type without an impl of the trait is an error that names the type and the trait:

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

Any number of types implement one trait, and a type implements any number of traits. An impl is declared in the namespace of the trait or of one of its types, so a trait declared in one package can be implemented for a type of another; a trait has one impl per type, or tuple of types, across all packages.

28.4 Dispatch on several arguments

trait_method(params, dispatch = c("x", "y")) names the arguments a method dispatches on; every method of a trait dispatches on the same number. An impl gives a list of types, one per dispatched argument it specializes, by position or by name:

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

Snap <- new_trait(
  "Snap",
  methods = list(
    snap = trait_method(params(x, grid), dispatch = c("x", "grid"))
  )
)

impl(
  Snap,
  list(Interval, Grid),
  methods = list(
    snap = function(x, grid) {
      Interval(
        lo = floor(x$lo / grid$step) * grid$step,
        hi = ceiling(x$hi / grid$step) * grid$step
      )
    }
  )
)

Snap@snap(Interval(lo = 0.3, hi = 1.6), Grid(step = 0.5))
<demo::Interval>
  lo: 0
  hi: 2

The impl for a tuple of types provides every method of the trait, as for one type. In Rust, the trait has a type parameter per dispatched argument after the first: impl Snap<Grid> for Interval. A trait that dispatches on several arguments has no tag member and is not the trait of a dyn() field.

28.5 Fields of any implementor

dyn(Trait) declares a field that holds a value of any type that implements the trait, or that extends a type that does. A trait with a tag member, new_trait(tag = ), names each implementor in its JSON by a tag value: the impl’s tag_value, or else the type’s name:

Algorithm <- new_trait(
  "Algorithm",
  methods = list(label = trait_method(params(x))),
  tag = "algorithm"
)

Glmnet <- new_struct("Glmnet", fields = list(alpha = type_double(min = 0, max = 1)))
Cart <- new_struct("Cart", fields = list(depth = type_integer(min = 1L)))

impl(
  Algorithm,
  Glmnet,
  methods = list(label = function(x) sprintf("elastic net, alpha %.1f", x$alpha)),
  tag_value = "GLMNET"
)
impl(
  Algorithm,
  Cart,
  methods = list(label = function(x) sprintf("tree of depth %d", x$depth))
)

Model <- new_struct("Model", fields = list(algorithm = dyn(Algorithm)))

model <- Model(algorithm = Glmnet(alpha = 0.5))
Algorithm@label(model$algorithm)
[1] "elastic net, alpha 0.5"
cat(r8to_json(model))
{"$type":"demo::Model","$types":{"demo::Glmnet":1,"demo::Model":1},"$declarations":{"demo::Glmnet":"sha256:91e1d8441bbcc8b6a565bd7c41cf30cf0d92600bc803dce2fda2145c4abd99dc","demo::Model":"sha256:55b5e6781da3ac64064e7b0e65063580e8d9872ab7f696499a749e4859545e2b"},"algorithm":{"alpha":0.5,"algorithm":"GLMNET"}}

A value of a type without an impl of the trait is an error. Tag values are names and are unique among a trait’s implementors; an implementor in another namespace writes its namespace first, "rtemis.extra::Boost".

A tag value that no registered implementor writes is an error that lists the tag values. A document whose "$types" names a type that no loaded package declares is an error that names the installed package declaring its namespace, which r8from_json(load = ) loads before the read:

r8from_json(
  Model,
  '{"$type": "demo::Model", "$types": {"demo::Model": 1},
    "algorithm": {"algorithm": "Forest", "trees": 100}}'
)
Error:
! Cannot read `demo::Model`: 1 problem
- `algorithm`: no registered implementor of `demo::Algorithm` has the tag value `Forest`; the registered tag values are `GLMNET`, `Cart`. [unknown_type]

r8schema(Model, closed = TRUE) writes the JSON Schema of Model with the field as the closed list of the implementors registered in the session.

28.6 Required fields

A trait may require fields of every implementor, so that code receiving a dyn() value of the trait reads them. new_trait(required_fields = ) names each field and its type; an implementor is a struct whose field of that name has a type that fits: the same type, T or option(T) for option(T), a subtype for subtype(), or an implementor for dyn(). A constraint narrows nothing: a field of type_double(min = 0) fits type_double(min = 0) only.

Measured <- new_trait(
  "Measured",
  methods = list(span = trait_method(params(x))),
  required_fields = list(lo = type_double(), hi = type_double())
)

impl(Measured, Interval, methods = list(span = function(x) x$hi - x$lo))

Measured@span(Interval(lo = 0, hi = 2))
[1] 2
Point <- new_struct("Point", fields = list(x = type_double()))
impl(Measured, Point, methods = list(span = function(x) 0))
Error:
! Declaration of `impl demo::Measured for demo::Point` failed:
- `demo::Measured` requires the field `lo`, which `demo::Point` does not have [required_field_missing at /target]
- `demo::Measured` requires the field `hi`, which `demo::Point` does not have [required_field_missing at /target]

A struct that extends an implementor holds its parent’s fields, so it meets the requirement as it inherits the impl. A struct declared again without a field that a trait it implements requires is an error, and so is a trait declared again with a requirement that an implementor does not meet.

© 2026 E.D. Gennatas