Learn R Programming

matchr (version 0.1.0)

bang: Extract Result or Return

Description

Returns the value contained inside of an Result or Option Enum or returns if failure.

Usage

# S3 method for Result
!(x, ...)

# S3 method for Option !(x, ...)

Arguments

x

Enumerated value of type Result or Option to unwrap

...

objects to be passed to methods.

Value

an object of any class or x if failure.

Functions

  • !.Result: Unwrap Result if Ok, otherwise return the Err variant in the parent function.

  • !.Option: Unwrap Option if Some, otherwise return the None variant in the parent function.

Details

This is similar to unwrap for Result and Option objects. However, an Err or None variant does not cause execution to stop. Instead, the parent function immediately returns the Enum intact. Inspired by the ? operator in Rust.

Examples

Run this code
# NOT RUN {
is_big <- function(x) {
  if (x > 10) return(Ok(x))
  Err("This is small!")
}

# If 'x' is greater than 10, the value will be printed.
# Otherwise, an error is returned.
print_big <- function(x) {
  print(!is_big(x))
}

# }

Run the code above in your browser using DataLab