Skip to content

Commit

Permalink
Add a document about optional arg (#247)
Browse files Browse the repository at this point in the history
  • Loading branch information
yutannihilation committed May 16, 2024
1 parent 2f4ae22 commit ebccac9
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 2 deletions.
3 changes: 2 additions & 1 deletion book/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
31 changes: 31 additions & 0 deletions book/src/optional_arg.md
Original file line number Diff line number Diff line change
@@ -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<IntegerSexp>) -> savvy::Result<Sexp> {
if let Some(x) = x {
x.iter().sum::<i32>().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
```
1 change: 1 addition & 0 deletions book/src/savvy_macro.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<savvy::Sexp>` for the case of some return value of R object
Expand Down
2 changes: 1 addition & 1 deletion book/src/scalar.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Handling Salars
# Handling Scalar

## Input

Expand Down

0 comments on commit ebccac9

Please sign in to comment.