Skip to content

Generic unions #506

Open
Open

Description

@mjskay

While I was waiting on #353 and #365, I started playing with an alternative approach to group generics in a package I am working on. I think this approach may be simpler than the current proposal, and also offer several benefits.

The basic idea is to add a general mechanism by which people can define methods on sets of generics at once. This could be implemented within method<-, or using a separate function.

The simple (probably not robust) implementation I am currently using looks like this:

#' Define methods on a group of generics
#'
#' Takes a list of generic functions and defines the same function for each,
#' allowing use of `.Generic` in the function body to refer to the actual generic.
#' @param generics a list of [symbol]s (such as returned by [expression()]),
#' each of which should correspond to a generic function, or the S4 definition
#' of a group generic, such as [`Compare`].
#' @param signature A method signature (see [`method<-`])
#' @param value A function implementing each `generic` for the given `signature`.
#' In each method, the variable `.Generic` in the method's environment will
#' refer to the generic function.
#' @noRd
`group_method<-` = \(generics, signature, value) {
  .generics = if (is(generics, "groupGenericFunction")) {
    lapply(getGroupMembers(generics), as.symbol)
  } else {
    generics
  }

  for (generic in .generics) {
    f = value
    environment(f) = new.env(parent = environment(value))
    environment(f)$.Generic = get(generic, mode = "function")
    eval(bquote(
      method(.(generic), signature) <<- f
    ))
  }
  invisible(generics)
}

Then you can use any existing S4 group generic as follows (say on a toy numeric class, "MyNum"):

group_method(Compare, list(MyNum, MyNum)) = \(e1, e2) MyNum(value = .Generic(e1@value, e2@value))

Since this generates all the specific methods (instead of creating a parallel dispatch on group generics), I think it makes dispatch easier to understand and easier to extend when creating class hierarchies.

It also avoids some of the ugliness common to S3 / S4 group generics code, like switch statements singling out one or two methods that operate differently. Instead, you would just define the specific methods you want to create as a separate group. e.g. if I just wanted to override inequalities, I might do:

inequalities = expression(`<`, `<=`, `>`, `>=`)    # or probably new_group_generic(...) or something
group_method(inequalities, list(MyNum, MyNum)) = \(e1, e2) MyNum(value = .Generic(e1@value, e2@value))

This also avoids the need for a method to look up the actual generic function inside the implementation, and allows users to create their own groups of generics as needed.

Activity

  1. hadley commented on Jun 18, 2026

    @hadley
    Member

    I like this because it feels like the same approach as class unions. We could even call them generic unions and provide a few built-ins. Hmmm, and we could make them work with method<- so we wouldn't need a new function.

    method(generic_Compare, list(MyNum, MyNum)) <- \(e1, e2) MyNum(value = .Generic(e1@value, e2@value))
    method(all | any, MyNum) <- \(...) .Generic(...1@value)
  2. hadley commented on Jun 20, 2026

    @hadley
  3. hadley commented on Jun 20, 2026

    @hadley
    Member

    A generic union is the generic-side analogue of a class union: registering a method on a generic union is short-hand for registering that method on each member. Inside the method, S7_generic_fun() (from #681) recovers which generic actually dispatched. This makes it convenient to implement methods which have the same "shape" en masse:

    MyNum := new_class(properties = list(value = class_double))
    
    # Existing group generics have their own helpers
    method(generic_Compare, list(MyNum, MyNum)) <- function(e1, e2, ...) {
      op <- S7_generic_fun()
      op(e1@value, e2@value)
    }
    
    # Or use `|` to create unions on the fly
    double := new_generic("double", "x")
    negate := new_generic("negate", "x")
    method(double | negate, MyNum) <- function(x, ...) {
      MyNum(value = S7_generic_fun()(x@value))
    }
    
    # But base/S3 generics require an explicit call
    # (because we don't want to override | for all functions)
    plus_minus <- new_generic_union(`+`, `-`)
    
    method(plus_minus, list(MyNum, MyNum)) <- function(e1, e2, ...) {
      op <- S7_generic_fun()
      MyNum(value = op(e1@value, e2@value))
    }
    method(plus_minus, list(MyNum, class_missing)) <- function(e1, e2, ...) {
      op <- S7_generic_fun()
      MyNum(value = op(e1@value))
    }

    Comparison with S3 group generics

    A generic union is a registration-time macro: method(union, sig) <- f
    expands to N ordinary per-generic methods. An S3 group generic (Ops.MyNum) is
    a runtime dispatch entity — one function, found via inheritance, with
    .Generic available. For contrast, the union examples above written as a group generic:

    Ops.MyNum <- function(e1, e2) {
      if (.Generic %in% c("+", "-") && missing(e2)) {
        MyNum(value = get(.Generic)(e1@value))           # unary
      } else if (.Generic %in% c("<", ">", "<=", ">=", "==", "!=")) {
        get(.Generic)(e1@value, e2@value)                # comparison -> logical
      } else {
        MyNum(value = get(.Generic)(e1@value, e2@value)) # arithmetic
      }
    }

    So there are some disadvantages to this approach too:

    1. Many more methods: for existing group generics you only need to register
      one method; with generic unions you need to register many. This makes
      registration more expensive and introspection harder to understand.

    2. Individual base-op methods currnetly route through S7's method-ops.R
      bridge. We'd need to think through how that changes with generic unions

  4. changed the title [-]Custom group generics (and maybe simpler group generics)[/-] [+]Generic unions[/+] on Jul 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions