27

In the following sample program, is there any way I could avoid having to define map2?

fn map2<T, U, V, F: Fn(T, U) -> V>(f: F, a: Option<T>, b: Option<U>) -> Option<V> {
    match a {
        Some(x) => match b {
            Some(y) => Some(f(x, y)),
            None => None,
        },
        None => None,
    }
}

fn main() {
    let a = Some(5);
    let b = Some(10);
    let f = |a, b| {
        a + b
    };
    let res = map2(f, a, b);
    println!("{:?}", res);
    // prints Some(15)
}

For people who also speak Haskell, I guess this question could also be phrased as "Is there any tool we can use instead of liftM2 in Rust?"

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
Erik Vesteraas
  • 4,517
  • 1
  • 22
  • 36

7 Answers7

31

I don't believe there's a direct function equivalent to liftM2, but you can combine Option::and_then and Option::map like this:

fn main() {
    let a = Some(5);
    let b = Some(10);
    let f = |a, b| {
        a + b
    };

    println!("{:?}", a.and_then(|a| b.map(|b| f(a, b))));
}

Output:

Some(15)
Dogbert
  • 200,802
  • 40
  • 378
  • 386
  • Thanks, that's actually a pretty good solution for when you only need to do this once or twice. Probably still worth it to define the function in some cases, though. – Erik Vesteraas Nov 18 '15 at 18:00
  • 2
    Another option that's a little longer but maybe easier to follow: `a.and_then(|a| b.and_then(|b| Some(f(a, b))))` – Jack O'Connor Jul 02 '18 at 17:41
12

As of Rust 1.46.0, you can use Option::zip:

fn map2<T, U, V, F: Fn(T, U) -> V>(f: F, a: Option<T>, b: Option<U>) -> Option<V> {
    match a.zip(b) {
        Some((x, y)) => Some(f(x, y)),
        None => None,
    }
}

This can be combined with Option::map, as shown in other answers:

fn map2<T, U, V, F: Fn(T, U) -> V>(f: F, a: Option<T>, b: Option<U>) -> Option<V> {
    a.zip(b).map(|(x, y)| f(x, y))
}
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
10

I don't know if you can get down to one line (Edit: oh the accepted answer gets it down to one line nicely), but you can avoid the nested match by matching on a tuple:

let a = Some(5);
let b = Some(10);
let f = |a, b| {
    a + b
};
let res = match (a, b) {
    (Some(a), Some(b)) => Some(f(a, b)),
    _ => None,
};
println!("{:?}", res);
// prints Some(15)
Jack O'Connor
  • 8,874
  • 3
  • 45
  • 48
  • I find this to be incomplete. If a or b is `None` this returns `None` where it should return either `Some(5)` or `Some(10)` respectively. – RubberDuck Jul 01 '18 at 14:57
  • 3
    I'm not sure it should. Note that both the example in the original question, and the `and_then`+`map` example above, return `None` if *either* argument is `None`. In general, if the return type of `f` is different from the type of its arguments, it might not be possible to return anything other than `None`. That said, if you want the fallback in this case, you can replace the `_ => None` clause with `_ => a.or(b)`. – Jack O'Connor Jul 02 '18 at 17:38
6

You can use the fact that Options can be iterated over. Iterate over both options, zip them together, and map the resulting iterator over your function.

fn main() {
    let a = Some(5);
    let b = Some(10);
    let f = |(a, b)| {
        a + b
    };
    let res = a.iter().zip(b.iter()).map(f).next();
    println!("{:?}", res);
    // prints Some(15)
}

This required a modification of f, so the arguments are merged into a single tuple-argument. It would be possible without modifying f, by directly mapping over |args| f.call(args), but then you would have to specify the closure kind of f.

oli_obk
  • 25,579
  • 3
  • 73
  • 89
5
let num_maybe = Some(5);
let num_maybe2 = Some(10);
let f = |a, b| {
    a + b
};

Option 1

if let (Some(a), Some(b)) = (num_maybe, num_maybe2) {
    f(a, b)
}

Option 2

num_maybe.and_then(|a| num_maybe2.map(|b| f(a, b))

Option 3

[num_maybe, num_maybe2].into_iter().flatten().fold(0, f)
Ben
  • 24,480
  • 2
  • 22
  • 28
  • Your "option 2" is already present in [the highest-voted answer](https://stackoverflow.com/a/33779802/155423) – Shepmaster Jun 21 '19 at 14:47
5

You can use an immediately invoked function expression (IIFE) combined with the ? (try) operator:

fn main() {
    let a = Some(5);
    let b = Some(10);
    let f = |a, b| a + b;

    let res = (|| Some(f(a?, b?)))();

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

In the future, you can use try blocks:

#![feature(try_blocks)]

fn main() {
    let a = Some(5);
    let b = Some(10);
    let f = |a, b| a + b;

    let res: Option<_> = try { f(a?, b?) };

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

See also:

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
  • Well that's pretty neat. Even when it is worth it to define `map2`, `Some(f(a?, b?))` is a much nicer implementation than the one I wrote back in 2015. – Erik Vesteraas May 20 '20 at 09:58
0

I stumbled upon this thread and didn't find the most obvious and straightforward one-liner solution based on zip.

let one = Some(1);
let two = Some(2);
let sum = one.zip(two).map(|(a, b)| a + b);
assert_eq!(sum, Some(3));

let two: Option<i32> = None;
let sum = one.zip(two).map(|(a, b)| a + b);
assert_eq!(sum, None);

There's also the zip_with variant which is marked as unstable right now.

let sum = one.zip_with(two, |a, b| a + b);
Lord of the Goo
  • 1,104
  • 14
  • 28