Some programming languages, e.g. Swift, have special “optional” types. These are types the represent elements that either contain a value of some other type or contain nothing at all. It is a way of computing with the possibility that some operations cannot be done and then propagating that along in the computations.

We can use pmatch to implement something similar in R. I will use three types instead of two, to represent no value, NONE, some value, VALUE(val), or some error ERROR(err):

We can now define a function that catches exceptions and translate them into ERROR() objects:

With this function the control flow when we want to compute something that might go wrong can be made a bit simpler. We no longer need a callback error handler; instead we can inspect the value returned by try in a cases call:

To extract the value of an expression after we have computed on optional values we can define this function:

Computing with optional values

Computing on optional values is more interesting if we can make it relatively transparent that this is what we are doing. For arithmetic expressions we can do this by defining operations on these types. A sensible way is to return errors if we see those, then NONE if we see one of those, and otherwise use VALUE:

Ops.OPT <- function(e1, e2) {
    cases(..(e1, e2),
          ..(ERROR(err), .)        -> ERROR(err),
          ..(., ERROR(err))        -> ERROR(err),
          ..(NONE, .)              -> NONE,
          ..(., NONE)              -> NONE,
          ..(VALUE(v1), VALUE(v2)) -> VALUE(, list(v1, v2))),
          ..(VALUE(v1), v2)        -> VALUE(, list(v1, v2))),
          ..(v1, VALUE(v2))        -> VALUE(, list(v1, v2)))

The last two cases here handles when we combine an optional value with a value from the underlying type. Because of the last two cases we do not need to explicitly translate a value into a VALUE(). With this group function defined we can use optional values in expressions.

For mathematical functions, such as log or exp, we can also define versions for optional types:

Function calls

Arithmetic is one thing, but we are probably more likely to use optional values for more complex computations? We can wrap expressions in a function to propagate options: