вторник, 2 марта 2021 г.

Typer - yet another approach for types verification in R

Introduction


In this article I would like to describe my new R package - typer - which allows to describe function input & output parameter types and verify actual parameter values during execution.

R is dynamically typed programming language. On one hand, this simplifies experimenting and writing code in REPL style. On other hand, it may cause problems if code is going to be reused. For example, in absence of type definitions any value can be passed into function call which may cause unexpected behavior.

Here is simple illustration:

func <- function(a, b) {
    return(a + b)
}

func(1, "1") # This will throw error
func(1, TRUE) # This may result in incorrect behaviour

There are multiple ways how to fight this problem. The most common one is to perform simple checks of input params at the beginning of the function like below.

func <- function (a, b) {

  if (is.numeric(a)) stop("a must be numeric")
  if (is.numeric(b)) stop("b must be numeric")

  return (a + b)
}

func(1, "1") # This will throw clear error
func(1, TRUE) # This will throw clear error

There are also some packages which simplify such checks. The good example here is checkmate package. It allows writing easy-to-understand and fast assertions on function input parameter values.

This is how our sample function may look like with asserts from checkmate package:

func <- function (a, b) {

  assertNumeric(a)
  assertNumeric(b)

  return (a + b)
}

Typer

The idea of typer package is to provide ability to describe function parameters in declarative way. Then this info can be used to verify actual parameter values during function execution. It also can be used for documents generation (as alternative for roxygen comments).