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 case_func call:

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:

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:

log(ERROR("foo"))
#> ERROR(err = foo)
exp(NONE)
#> NONE