This package adds an
optional type, similar to
Option in F#, OCaml and Scala, to
Haskell, and to nullable types in
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
<- option(5) a class(a)
##  "optional"
Operators and print will have the same behavior with an
optional than with its base type.
##  TRUE
##  5
option(obj) and that
To check whether an
optional object is set to a value or
none, one can use the function
<- option(5) a some(a)
##  TRUE
<- none a some(a)
##  FALSE
Given a function
f(), to handle properly
optional arguments and wraps its return type into an
optional, one should use
f_opt <- make_opt(f)
optionalargument passed to
f_opt()will be converted to its original type before being sent to
f(). If one or more of them is
none, several behaviors are available (see
f()returns null, or if an error is thrown during its execution, then
none. Else it will return
<- make_opt(c) c_opt c_opt(option(2), none, option(5))
##  2 5
##  "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, ...
variable matches a
result-function is called. For comparing optional types, it
is a better habit to use
match_with() rather than a
## Warning: le package 'magrittr' a été compilé avec la version R 4.1.3
<- 5 a match_with(a, %>% option(.), paste, . function() "Error!" none, )
##  "5"
patterncan be either:
variableis in the list),
magrittrfunctional sequence that matches if it returns
variable. The dot
.denotes the variable to be matched.
result-functiontakes no arguments, it will be called as is. Else, the only argument that will be sent is
variable. You can also use the fallthrough function
fallthrough()to permit the matching to continue even if the current pattern is matched.
<- 4 a match_with(a, 1, function() "Matched exact value", list(2, 3, 4), fallthrough(function() "Matched in list"), %>% if (. > 3)., function(x) paste0("Matched in condition: ",x,">3") . )
##  "Matched in list" "Matched in condition: 4>3"