extendr / extendr.github.io

https://extendr.github.io/
MIT License
5 stars 3 forks source link

NA handling #27

Open JosiahParry opened 4 months ago

JosiahParry commented 4 months ago

Use extendr types for inputs which allow for missing values. Illustrate using match or ifelse statements to handle missing values. Discuss options:

Ilia-Kosenkov commented 4 months ago

We also have Nullable<T> to handle explicit NULL values

JosiahParry commented 4 months ago

TIL https://extendr.github.io/extendr/extendr_api/wrapper/nullable/enum.Nullable.html !

JosiahParry commented 4 months ago

Here's a minimal example of using this. @Ilia-Kosenkov what would you say the desired use pattern is for Nullable?

I can see it being helpful in my code here: https://github.com/JosiahParry/rsgeo/blob/32d0d7e2f0faab349b5261f964a0091760b55fcd/src/rust/src/boundary.rs#L149-L159

struct MyStruct();

#[extendr]
impl MyStruct {
}

#[extendr]
fn mynull(x: bool) -> Nullable<MyStruct> {
    match x {
        true => Nullable::NotNull(MyStruct()),
        false => Nullable::Null,
    }
}
mynull(TRUE)
#> <pointer: 0x1>
#>   attr(,"class")
#> [1] "MyStruct"
mynull(FALSE)
#> NULL
Ilia-Kosenkov commented 4 months ago

I think one of the best use-cases is NULL default values, e.g.

#[extendr(use_try_from = true)]
fn with_optional_input(#[default = "NULL"] idx : Nullable<Integers>) -> Integers {
    match idx {
        NotNull(x) => x,
        Null => (0..5).collect::<Integers>() /* do not remember the syntax */
    }
}