---
title: "Creating semantic vector types with vecvec"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Creating semantic vector types with vecvec}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
```

vecvec is a foundation for packages that need one vector to hold several
related types. [mixtime](https://pkg.mitchelloharawild.com/mixtime/) uses it
for time at different granularities (days, months, years), and
[distributional](https://pkg.mitchelloharawild.com/distributional/) for
distributions of different families (Normal, Poisson, ...).

Both follow the same pattern:

1. An **inner type**: an ordinary vector class for one variant, carrying its
   variant in attributes (a mixtime chronon, a distribution family). This is
   where the semantics live.
2. A **container**: an S7 subclass of `class_vecvec` that stores many inner
   vectors side by side and behaves like a single vector.

This vignette builds a small example, a `money` vector holding amounts in
different currencies.

```{r setup, message = FALSE}
library(vecvec)
library(S7)
library(vctrs)
```

## The inner type

Each currency is an `amount` vector: doubles with a `currency` attribute. Its
methods define what an amount *means*, e.g. you can't add AUD to EUR.

```{r inner}
new_amount <- function(x = double(), currency = "USD") {
  structure(as.double(x), currency = currency, class = "amount")
}

format.amount <- function(x, ...) {
  paste(formatC(unclass(x), format = "f", digits = 2), attr(x, "currency"))
}

Ops.amount <- function(e1, e2) {
  cur <- unique(c(attr(e1, "currency"), attr(e2, "currency")))
  if (length(cur) > 1) {
    stop("Can't combine ", paste(cur, collapse = " and "), ".", call. = FALSE)
  }
  out <- get(.Generic)(unclass(e1), unclass(e2))
  if (.Generic %in% c("+", "-", "*", "/")) new_amount(out, cur) else out
}
```

Nothing here knows about vecvec. In mixtime the inner types are `mt_time`
classes; in distributional they are `vctrs_rcrd`s of distribution parameters.

## The container

The container is an S7 class with `class_vecvec` as its parent, a
user-facing constructor that wraps a single inner vector, and a type name
for printing.

```{r container}
class_money <- new_class(
  "money",
  parent = class_vecvec,
  # Set automatically when defined inside a package
  package = "mypkg"
)

money <- function(x = double(), currency = "USD") {
  class_money(list(new_amount(x, currency)))
}

method(vec_ptype_full, class_money) <- function(x, ...) "money"
method(vec_ptype_abbr, class_money) <- function(x, ...) "money"
```

Mixed vectors are made by combining single-type vectors.

```{r combine}
x <- c(money(c(10, 25), "AUD"), money(5, "EUR"))
x
```

## Registering with vctrs

Call `vecvec_register()` in your package's `.onLoad()` so the subclass works
with vctrs (and so with tibbles, dplyr and tidyr). Since S7 copies the parent
class into your class when your package is built, mixtime also rebuilds its
class here, so it always uses the installed version of vecvec.

```{r onload, eval = FALSE}
.onLoad <- function(libname, pkgname) {
  class_money <<- S7::new_class("money", parent = vecvec::class_vecvec)
  S7::methods_register()
  vecvec::vecvec_register(
    class_money,
    f_ptype2 = vec_ptype2_money,
    f_cast_to = vec_cast_to_money
  )
}
```

The optional functions decide how other types combine with yours:

* `f_ptype2` gives the common type. Return an empty container holding no
  types, `class_money()`, to mean "money of any currency".
* `f_cast_to` casts other vectors to your type (here, numbers become USD).
* `f_cast_from` casts your type to others (by default with `unvecvec()`).

```{r register}
vec_ptype2_money <- function(x, y, ...) class_money()

vec_cast_to_money <- function(x, to, ...) {
  if (S7_inherits(x, class_money)) return(x)
  if (is.numeric(x)) return(money(x))
  stop_incompatible_cast(x, to, x_arg = "", to_arg = "")
}

vecvec_register(
  class_money,
  f_ptype2 = vec_ptype2_money,
  f_cast_to = vec_cast_to_money
)

vec_c(x, 1)
tibble::tibble(x)
```

If you write your own `vec_cast()` method between two vectors of your class,
it must return `vecvec_cast(x, to)`.

## What comes for free

Subsetting, `rep()`, printing, sorting and the `Ops`/`Math` group generics
are inherited from vecvec. Each operation is applied to every inner vector,
so the inner type's methods decide the result.

```{r free, error = TRUE}
x * 2
x > 7
x + c(money(c(1, 2), "AUD"), money(3, "EUR"))
x + money(1, "AUD")
```

Replicated values are stored once and only the index grows, so operations on
long, repetitive vectors stay cheap.

```{r rep}
str(rep(x, 1000)@x)
```

## Adding methods

Write each method for the inner type, then lift it to the container with
`vecvec_apply_fn()`. The result is simplified to `ptype` when given, otherwise
it stays a `money` vector. This is how mixtime defines most of its methods
(e.g. `method(time_round, class_mixtime) <- vecvec_apply_fn(time_round)`).

```{r apply-fn}
currency <- function(x) UseMethod("currency")
currency.amount <- function(x) rep(attr(x, "currency"), length(x))
method(currency, class_money) <- vecvec_apply_fn(currency, ptype = character())

currency(x)
```

For one-off transformations, `vecvec_apply()` applies a function to each inner
vector directly.

```{r apply}
vecvec_apply(x, function(a) new_amount(unclass(a) * 1.1, attr(a, "currency")))
```

When a method takes other vector arguments that line up with `x`, use
`vecvec_mapply()`. It calls `.f` once per group of positions that share an
inner vector, so `.f` must be vectorised. distributional uses this to evaluate
`density()`, `cdf()` and friends at per-element values.

```{r mapply}
within_budget <- function(x, limit) {
  vecvec_mapply(
    list(x, limit),
    function(amount, limit) unclass(amount) <= limit,
    ptype = logical()
  )
}
within_budget(x, c(20, 20, 10))
```

## Tips from mixtime and distributional

* **Cast inputs to `c()`.** vecvec stores non-vecvec inputs to `c()` and `[<-`
  as they are. Both packages add a `c()` method that casts them to their type
  first (numbers to degenerate distributions, for example).
* **Use `unvecvec()` to leave your type.** It flattens a container to its
  common type, which is how numeric results (means, positions) are returned.
* **Keep the inner type self-sufficient.** vecvec only moves vectors around;
  formatting, arithmetic and validity checks belong to the inner type, and
  vecvec applies them to each one.
