【发布时间】:2015-11-18 12:02:49
【问题描述】:
在下面的示例程序中,有什么方法可以避免定义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 的人,我想这个问题也可以表述为“我们可以使用任何工具来代替 Rust 中的 liftM2 吗?”
【问题讨论】: