我有一个可用的函数:
fn compose<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
move |x: A| g(f(x))
}
我希望在这种情况下使用柯里化,这样我就可以做到:
/* THIS */
compose(f)(g)(x)
/* Instead of this */
compose(f, g)(x)
是否有必要考虑制作一个宏来实现这一点呢?
compose(f)(g)(h)···(x)
我已经成功得到了一个与我想要的有点相似的东西:
fn compose<A, B, C, F: 'static, G: 'static>(f: F) -> impl Fn(G) -> Box<dyn Fn(A) -> C>
where
F: Fn(A) -> B + Copy,
G: Fn(B) -> C + Copy,
{
move |g: G| Box::new(move |x: A| g(f(x)))
}
let inc = |x| x + 1;
let mult2 = |x| x * 2;
let inc_compose = compose(inc);
println!("{}", inc_compose(mult2)(3)); // 8
现在有一个新问题:当基于我的
compose
函数创建高阶函数时,我需要根据另一个函数给该函数指定类型:let inc = |x: usize| x + 1;
let mult2 = |x: usize| x * 2;
let mult3 = |x: usize| x * 3;
let inc_compose = compose(inc);
println!("{}", inc_compose(mult2)(3)); // 8
println!("{}", inc_compose(mult3)(3)); // ERROR: [rustc E0308] [E] mismatched types
有没有办法避免这个错误?
这些类似的帖子都没有回答我的问题:
主要原因是我想使用柯里化来实现无参编程。
pipeline
感兴趣,这是一个流行的crate,提供了pipe!()
宏。 - Ibraheem Ahmed