是否有任何内置的“组合"方式?两个选项? [英] Is there any built in way to "combine" two Options?

查看:67
本文介绍了是否有任何内置的“组合"方式?两个选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例程序中,有什么办法可以避免定义map2?

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)
}

对于也会说 Haskell 的人,我想这个问题也可以表述为我们可以使用任何工具来代替 liftM2 在 Rust 中?"

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?"

推荐答案

我不相信有一个直接等同于 liftM2 的功能,但你可以结合 Option::and_thenOption::map 像这样:

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))));
}

输出:

Some(15)

这篇关于是否有任何内置的“组合"方式?两个选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆