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.
- Vapour
- R
type user: object {
name: char,
age: int
}
let ada: user = user(name = "Ada", age = 36)
ada = structure(
list(name = "Ada", age = 36),
class = c("user", "list")
)
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.
| Kind | Creates | Use it for |
|---|---|---|
object | named list | records with named fields |
struct | structure() | a value with named attributes |
dataframe | data.frame | tables |
list | unnamed list | collections of values |
[]type | list of a type | collections of one custom type |
matrix | matrix | matrices |
factor | factor | categorical values |
environment | environment | mutable 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.
- Vapour
- R
type book: object {
title: char,
pages: int
}
let b: book = book(title = "Dune", pages = 412)
b = structure(
list(title = "Dune", pages = 412),
class = c("book", "list")
)
Struct
A struct creates an R structure: one unnamed value, plus named
attributes. Use it to attach metadata to a vector.
- Vapour
- R
type measure: struct {
num,
unit: char
}
let height: measure = measure((1.62, 1.80), unit = "m")
print(height$unit)
height = structure(
c(1.62, 1.80),
unit = "m",
class = "measure"
)
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.
- Vapour
- R
type scores: dataframe {
name: char,
score: num
}
let s: scores = scores(
name = ("Ada", "Bob"),
score = (9.5, 7.0)
)
print(s$score)
s = structure(
data.frame(
name = c("Ada", "Bob"),
score = c(9.5, 7.0)
),
names = c("name", "score"),
class = c("scores", "data.frame")
)
print(s$score)
List
A list holds unnamed values of the types you list.
For named values, use an object.
- Vapour
- R
type tags: list { int | char }
let t: tags = tags(1, "urgent", 3)
t = structure(
list(1, "urgent", 3),
class = c("tags", "list")
)
Lists of a type
Put [] before a type to declare a list of that type.
This is the natural way to hold many records.
- Vapour
- R
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)
}
team = structure(
list(
structure(list(name = "Ada", age = 36), class = c("user", "list")),
structure(list(name = "Bob", age = 41), class = c("user", "list"))
),
class = c("users", "list")
)
for(member in team) {
print(member$name)
}
Matrix
A matrix takes a single type.
- Vapour
- R
type grid: matrix { int }
let g: grid = grid(1..4)
g = structure(
matrix(1:4),
class = c("grid", "matrix")
)
To fix its shape, add the @matrix decorator on the line before.
It accepts nrow, ncol, and byrow, which are passed to matrix().
- Vapour
- R
@matrix(nrow = 2, ncol = 2)
type grid: matrix { int }
let g: grid = grid(1..4)
g = structure(
matrix(1:4, nrow = 2, ncol = 2),
class = c("grid", "matrix")
)
Factor
A factor takes a single type.
The @factor decorator accepts levels, labels, exclude,
ordered, and nmax, which are passed to factor().
- Vapour
- R
@factor(levels = ("low", "high"), ordered = true)
type priority: factor { char }
let p: priority = priority(("low", "high", "low"))
p = structure(
factor(
c("low", "high", "low"),
levels = c("low", "high"),
ordered = TRUE
),
class = c("priority", "factor")
)
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.
- Vapour
- R
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
bump = function(c) {
stopifnot(!missing(c))
c$count = c$count + 1
}
clicks = structure(
list2env(list(count = 0), envir = new.env()),
class = c("counter", "environment")
)
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.
- Vapour
- R
@class(vehicle, thing)
type car: struct {
int,
name: char
}
let c: car = car(1, name = "Herbie")
print(class(c))
# [1] "vehicle" "thing"
c = structure(
1,
name = "Herbie",
class = c("vehicle", "thing")
)
print(class(c))
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, orenvironment. @matrix,@factor, and@environmentpass arguments to the R constructor,@classsets the class.
The precise rules are in the spec: type declarations, attributes, and decorators.