https://www.antoinechampion.com/
This package adds an optional
type, similar to Option
in F#, OCaml and Scala, to Maybe
in Haskell, and to nullable types in C#
.
It should be used instead of NULL
for values that might be missing or otherwise invalid.
This package also introduces pattern matching.
option
is an object wrapper which indicates whether the object is valid or not.
An optional variable can be set to option(object)
or to none
.
## [1] "optional"
Operators and print will have the same behavior with an optional
than with its base type.
## [1] TRUE
## [1] 5
Note that option(option(obj))
equals option(obj)
and that option(none)
equals FALSE
.
To check whether an optional
object is set to a value or to none
, one can use the function some()
.
## [1] TRUE
## [1] FALSE
Given a function f()
, to handle properly optional
arguments and wraps its return type into an optional
, one should use make_opt()
the following way:
f_opt <- make_opt(f)
- Every
optional
argument passed tof_opt()
will be converted to its original type before being sent tof()
. If one or more of them isnone
, several behaviors are available (see?make_opt
). - If
f()
returns null, or if an error is thrown during its execution, thenf_opt()
returnsnone
. Else it will returnoptional(f(...))
.
For instance:
## [1] 2 5
## [1] "None"
Patterns are used in many functional languages in order to process variables in an exhaustive way.
The syntax is the following:
match_with( variable,
pattern , result-function,
...
If variable
matches a pattern
, result-function
is called. For comparing optional types, it is a better habit to use match_with()
rather than a conditional statement.
## [1] "5"
- Each
pattern
can be either:- an object or a primitive type (direct comparison with
variable
), - a list (match if
variable
is in the list), - a
magrittr
functional sequence that matches if it returnsvariable
. The dot.
denotes the variable to be matched.
- an object or a primitive type (direct comparison with
- If
result-function
takes no arguments, it will be called as is. Else, the only argument that will be sent isvariable
. You can also use the fallthrough functionfallthrough()
to permit the matching to continue even if the current pattern is matched.
## [1] "Matched in list" "Matched in condition: 4>3"