The Maybe monad
the-maybe-monad.Rmd
library(chronicler){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)
#> Just
#> [1] 4m_sqrt(16) succeeds and returns Just 4. But
what happens if it fails?
m_sqrt("10")
#> Nothingm_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")
#> NOK! Value computed unsuccessfully:
#> ---------------
#> Nothing
#>
#> ---------------
#> This is an object of type `chronicle`.
#> Retrieve the value of this object with unveil(.c, "value").
#> To read the log of this object, call read_log(.c).and when computations succeed, Just values are also
returned:
r_sqrt <- record(sqrt)
r_sqrt(16)
#> OK! Value computed successfully:
#> ---------------
#> Just
#> [1] 4
#>
#> ---------------
#> This is an object of type `chronicle`.
#> Retrieve the value of this object with unveil(.c, "value").
#> To read the log of this object, call read_log(.c).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 unveil():
unveil(r_sqrt(16), "value")
#> [1] 4unveil() converts the value from the maybe
type to the underlying type of the object. Compare to:
(r_sqrt(16))$value
#> Just
#> [1] 4which returns the Just object. To learn more about
maybe, read the package’s readme which
provides a nice introduction.