The Maybe monad

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(chronicler)
library(maybe)

{chronicler} uses the {maybe} package under the hood; {maybe} implements the Maybe monad which provides an elegant solution to situations where functions fail. As an example, let’s consider the sqrt() function decorated using maybe():

m_sqrt <- maybe(sqrt)

m_sqrt(16)

m_sqrt(16) succeeds and returns Just 4. But what happens if it fails?

m_sqrt("10")

m_sqrt("10") returns Nothing because sqrt("10") would return an error. Using maybe() allows you to build safe functions that never fail; you can explicitely handle Nothing values instead of having the program crash and stop.

When a computation fails, functions decorated using record() also return Nothing:

r_sqrt <- record(sqrt)

r_sqrt("16")

and when computations succeed, Just values are also returned:

r_sqrt <- record(sqrt)

r_sqrt(16)

If Nothing is passed to a function decorated by record(), Nothing gets immediately returned.

Users of {chronicle} do not need to be familiar with the {maybe} package to use it, as conversion to and from maybe objects is handled automatically.

To recuperate the value from a chronicler object, users can use pick():

pick(r_sqrt(16), "value")

pick() converts the value from the maybe type to the underlying type of the object. Compare to:

(r_sqrt(16))$value

which returns the Just object. To learn more about {maybe}, read the package’s readme which provides a nice introduction.



Try the chronicler package in your browser

Any scripts or data that you put into this service are public.

chronicler documentation built on June 22, 2024, 11:30 a.m.