Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rust have an equivalent to Haskell's `sequence` function?

I am mapping over Vec such that each item becomes a Result. If any element is an Err then I want to terminate early and produce an Err, otherwise I want to produce an Ok containing the Vec<i32>.

let v = (1..10)
        .map( |n| {
            if n % 4 == 0 {
                Err("Too fourish!")
            }
            else {
                Ok(n)
            }
        }).collect::<Vec<_>>();


println!("{:?}", v);

In Haskell, I can use sequence. Is there an equivalent built-in Rust function?

like image 667
Peter Hall Avatar asked Nov 06 '15 11:11

Peter Hall


1 Answers

You can use the FromIterator implementation of Result for this:

fn main() {
    let v = (1..10)
        .map( |n| {
            if n % 4 == 0 {
                Err("Too fourish!")
            }
            else {
                Ok(n)
            }
        }).collect::<Result<Vec<_>, _>>();
    println!("{:?}", v);

    let v = (1..10)
        .map( |n| {
            if n % 4 == 4 { // impossible
                Err("Too fourish!")
            }
            else {
                Ok(n)
            }
        }).collect::<Result<Vec<_>, _>>();
    println!("{:?}", v);
}

Output:

Err("Too fourish!")
Ok([1, 2, 3, 4, 5, 6, 7, 8, 9])

More info: https://doc.rust-lang.org/std/result/enum.Result.html#implementations

like image 64
Dogbert Avatar answered Oct 18 '22 19:10

Dogbert