Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to express "result 1 if okay or result 2" as a chain of combinators?

Imagine I have two functions which return Results and would like to select the first result if Ok and otherwise the second result. Something like the following:

fn primary() -> Result<String, ()> {
    Err(())
}

fn alternative() -> Result<String, ()> {
    Ok("alternative".to_string())
}

fn using_match() -> Result<String, ()> {
    Ok(match primary() {
        Ok(string) => string,
        _ => alternative()?
    })
}

I’m struggling to find a way to express this as a chain of combinators. The following doesn’t work for the reason stated in the comment, but it captures the chain structure I’m trying to achieve:

fn combinator_attempt() -> Result<String, ()> {
    // this is wrong because the closure must return a String
    //                                               v----------------v
    Ok(primary().map(|string| string).unwrap_or_else(|_| alternative()?))
}

Is there an idiomatic way to express this? For extra points, what is a good way to select the first Ok (or last Err) from a chain of (three or more) possible operations?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Result::or_else method to make chains:

fn using_match() -> Result<String, ()> {
  primary().or_else(|_| alternative())
}

fn chain_three() -> Result<String, ()> {
  primary().or_else(|_| alternative()).or_else(|_| third_option())
}

Docs: https://doc.rust-lang.org/std/result/enum.Result.html#method.or_else

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading