Skip to main content
Version: Next

Custom types

R code is full of lists, data frames, and structures, and nothing checks their contents: a list can have any fields, and a typo in x$naem just returns NULL. Custom types let you describe the shape of your data once, then Vapour checks it everywhere.

Declaring a type​

Declare a type with type, a name, a colon, a kind, and its attributes.

type user: object {
name: char,
age: int
}

Declaring a type also gives you a constructor: a function of the same name that creates a value of that type.

type user: object {
name: char,
age: int
}

let ada: user = user(name = "Ada", age = 36)

The value gets a class named after its type, which is what makes methods work.

Attributes are checked​

Access attributes with $. Vapour checks that the attribute exists, and that what you assign to it has the right type.

type user: object {
name: char,
age: int
}

let ada: user = user(name = "Ada", age = 36)

ada$age = ada$age + 1 # fine

# error: `email` unknown attribute on `ada`
print(ada$email)

# error: left expects `int`, right returns `char`
ada$age = "old"

This works through nested attributes as well, e.g.: team$lead$name.

Kinds of types​

There's a kind for each common R structure. Pick the one that matches what you would build in R.

KindCreatesUse it for
objectnamed listrecords with named fields
structstructure()a value with named attributes
dataframedata.frametables
listunnamed listcollections of values
[]typelist of a typecollections of one custom type
matrixmatrixmatrices
factorfactorcategorical values
environmentenvironmentmutable state shared by reference

The kinds are only used to declare types: let x: list is invalid, declare a type with list and use that.

Object​

An object is a named list. Every attribute must be named.

type book: object {
title: char,
pages: int
}

let b: book = book(title = "Dune", pages = 412)

Struct​

A struct creates an R structure: one unnamed value, plus named attributes. Use it to attach metadata to a vector.

type measure: struct {
num,
unit: char
}

let height: measure = measure((1.62, 1.80), unit = "m")

print(height$unit)

The first, unnamed, entry is the type of the value, the others are its attributes.

Data frame​

A dataframe declares the name and type of each column.

type scores: dataframe {
name: char,
score: num
}

let s: scores = scores(
name = ("Ada", "Bob"),
score = (9.5, 7.0)
)

print(s$score)

List​

A list holds unnamed values of the types you list. For named values, use an object.

type tags: list { int | char }

let t: tags = tags(1, "urgent", 3)

Lists of a type​

Put [] before a type to declare a list of that type. This is the natural way to hold many records.

type user: object {
name: char,
age: int
}

type users: []user

let team: users = users(
user(name = "Ada", age = 36),
user(name = "Bob", age = 41)
)

for(let member: user in team) {
print(member$name)
}

Matrix​

A matrix takes a single type.

type grid: matrix { int }

let g: grid = grid(1..4)

To fix its shape, add the @matrix decorator on the line before. It accepts nrow, ncol, and byrow, which are passed to matrix().

@matrix(nrow = 2, ncol = 2)
type grid: matrix { int }

let g: grid = grid(1..4)

Factor​

A factor takes a single type. The @factor decorator accepts levels, labels, exclude, ordered, and nmax, which are passed to factor().

@factor(levels = ("low", "high"), ordered = true)
type priority: factor { char }

let p: priority = priority(("low", "high", "low"))

Environment​

An environment has typed attributes, like an object. The difference is that environments are passed by reference: a function that changes one changes it for everyone. Use them for mutable state, like a counter or a cache.

type counter: environment {
count: int
}

func bump(c: counter): null {
stopifnot(!missing(c))
c$count = c$count + 1
}

let clicks: counter = counter(count = 0)
bump(clicks)
bump(clicks)
print(clicks$count) # 2

The @environment decorator accepts hash, parent, and size, which are passed to new.env().

@environment(hash = true, size = 10)
type cache: environment {
hits: int
}

Which types can be looped over​

You can loop over vectors, list types, and [] types. Other kinds, like object and struct, cannot be looped over.

type user: object {
name: char,
age: int
}

let ada: user = user(name = "Ada", age = 36)

# error: type `user` cannot be iterated
for(let x: any in ada) {
print(x)
}

Classes​

By default a value's class is the name of its type, followed by the underlying R class, e.g.: c("user", "list") for an object, "measure" for a struct.

Change it with the @class decorator. This is useful when your type should inherit from an existing class.

@class(vehicle, thing)
type car: struct {
int,
name: char
}

let c: car = car(1, name = "Herbie")
print(class(c))
# [1] "vehicle" "thing"
warning

Don't name a type after an S3 class that already exists in R, e.g.: person from utils. R will dispatch that class's methods on your values, which can lead to strange behaviour.

Types from other packages​

Packages written in Vapour export their types (see packages). Use them with the package namespace, as you would a function.

let x: aPkg::theType = aPkg::theType(x = 1)

type wrapper: object {
inner: aPkg::theType
}

Recap​

  • type name: kind { ... } declares a type and a constructor function.
  • Attributes are accessed with $ and checked: name and type.
  • Choose the kind that matches the R structure: object, struct, dataframe, list, []type, matrix, factor, or environment.
  • @matrix, @factor, and @environment pass arguments to the R constructor, @class sets the class.

The precise rules are in the spec: type declarations, attributes, and decorators.