'Is there an option type?

This language being multi-paradigm, I wonder if there exists an Option type in R (Some/None), natively or in a package.

It would be similar to F#, or to C# nullables.

So instead of using NULL, we would have a type wrapper:

square <- function(x) {
  if (class(x) == "numeric")
    return( Some(x*x) )
  else
    return( None )
}

square(2)
> 4
square("foo")
> None

Then you could also filter it out:

if (square(x) == Some(4))
  print(x)

If it doesn't exist, did anyone tried to implement it?



Solution 1:[1]

I couldn't find an implementation of such (handy) types in R, so I created mine.

UPDATE: Now available as a package on github and on the CRAN.


Quickstart:

An optional variable can be set to some(object) or to none.

a <- some(5)
class(a)
## [1] "optional"

Operators and print will have the same behavior with an optional than with its base type.

a == 5
## [1] TRUE
a
## [1] 5

Note that some(some(obj)) equals some(obj) and that some(none) equals FALSE.


To make an existing function accept optionals as arguments and also return an optional, one can use make_opt():

c_opt <- make_opt(c)
c_opt(some(2), none, some(5))
## [1] 2 5
c_opt()
## [1] "None"

Bonus part: I also introduced pattern matching from functional languages, with match_with:

match_with( variable,
pattern , result-function,
...

This is meant to be used with Magrittr package if you want to get a syntax as close as the functional match with:

a <- 5
match_with(a,
  . %>% some(.),          print,
  none,                   function() print("Error!")
)

Solution 2:[2]

What about the maybe type within package monads which I think is more useful. I had a look at optional in CRAN but it is not a monad which limits its usefulness.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 David Tam