Skip to content

declare() type hints #169

@t-kalinowski

Description

@t-kalinowski

It would be nice to use declare() for type hints, following the style of a Fortran subroutine type manifest. These type declarations could then:

  • Be parsed by roxygen to autogenerate or augment parameter documentation
  • Be used by a compiler to compile the R function to machine code
  • Be used by a runtime checker to validate arguments

Example syntax:

fun <- function(a, b, c, d, e) {
  declare(
    a = integer(1),      # Vector of a specific length
    b = integer(NA),     # Vector of any length
    c = integer(c(NA, 3)), # Matrix with 3 columns and any number of rows
    d = integer(c(NA, NA, NA)), # 3D array of any size
    
    # Data frame with columns `name` and `age`
    # and optionally other columns `...` that are ignored
    e = data.frame(
      name = character(NA),
      age = integer(NA),
      ...
    ),
    
    # Declare return type
    return = logical(1)
  )
  
  TRUE
}

Some additional, more experimental syntax could also be supported:

  • Length constraints:
declare(
  a = integer(.>3),           # Vector with a length constraint
  b = integer(10 <= . <= 20)  # Vector with a more complex length constraint
)
  • Union types, which could also be a way to specify optional (NULLable) args:
declare(
  x = union(integer(1), character(1))
  # or 
  x = integer(1) || character(1)
  
  # optional arg
  x = integer(1) || NULL
)
  • Function types:
    Include a way to specify function parameters and their expected signatures:
declare(
  f = function(x = numeric(1)) -> logical(1)
)
  • Named dimensions:
    For multidimensional arrays, allow naming dimensions for clarity :
declare(
  matrix = numeric(c(rows = NA, cols = 3))
)
  • Value constraints:
declare(
  age = integer(1, 0 <= . <= 120),
  color = character(1, . %in% c("red", "green", "blue"))
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions