diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index 2871dff3..8b0aeb45 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -12,7 +12,8 @@ - [`#[savvy]` macro](./savvy_macro.md) - [Handling Vector Input](./input.md) - [Handling Vector Output](./output.md) -- [Handling Scalars](./scalar.md) +- [Handling Scalar](./scalar.md) +- [Optional Argument](./optional_arg.md) - [Type-specific Topics](./type-overview.md) - [Integer, Real, String, Logical, And Complex](./atomic_types.md) - [List](./list.md) diff --git a/book/src/optional_arg.md b/book/src/optional_arg.md new file mode 100644 index 00000000..62793b08 --- /dev/null +++ b/book/src/optional_arg.md @@ -0,0 +1,31 @@ +# Optional Argument + +To represent an optional argument, you can wrap it with `Option`. Then, the +corresponding R function sets the default value of `NULL` on the argument. + +``` rust +#[savvy] +fn default_value_vec(x: Option) -> savvy::Result { + if let Some(x) = x { + x.iter().sum::().try_into() + } else { + (-1).try_into() + } +} +``` + +``` r +function(x = NULL) { + .Call(savvy_default_value_vec__impl, x) +} +``` + +This function works with or without the argument. + +``` r +default_value_vec(1:10) +#> [1] 55 + +default_value_vec() +#> [1] -1 +``` diff --git a/book/src/savvy_macro.md b/book/src/savvy_macro.md index 041767b0..9f9cc54f 100644 --- a/book/src/savvy_macro.md +++ b/book/src/savvy_macro.md @@ -42,6 +42,7 @@ function must satisfy the following conditions: * a corresponding Rust type for scalar (e.g., `i32` and `f64`) * a user-defined struct marked with `#[savvy]` (`&T`, `&mut T`, or `T`) * a user-defined enum marked with `#[savvy]` (`&T`, or `T`) + * any of above wrapped with `Option` (this is translated as an optional arg) * The function's return value must be either * `savvy::Result<()>` for the case of no actual return value * `savvy::Result` for the case of some return value of R object diff --git a/book/src/scalar.md b/book/src/scalar.md index 3fd7c0ec..6404c70f 100644 --- a/book/src/scalar.md +++ b/book/src/scalar.md @@ -1,4 +1,4 @@ -# Handling Salars +# Handling Scalar ## Input