I am trying to get a list of partially applied functions, like so:
fn partially_applied() -> Vec<Box<dyn Fn(u32) -> u32>> {
let xs = vec![1_u32, 2, 3];
xs.into_iter().map(|x| Box::new(move |y| x + y)).collect()
}
The compiler yields an error to me:
error[E0277]: a value of type std::vec::Vec<std::boxed::Box<dyn std::ops::Fn(u32) -> u32>> cannot be built from an iterator over elements of type std::boxed::Box<[closure@src/main.rs:4:41: 4:57]>
The subsequent attempts also did not work:
1.
fn partially_applied_with_explicit_collect_type() -> Vec<Box<dyn Fn(u32) -> u32>> {
let xs = vec![1_u32, 2, 3];
xs.into_iter().map(|x| Box::new(move |y| x + y)).collect::<Vec<Box<dyn Fn(u32) -> u32>>>()
}
fn partially_applied_with_explicit_vec_type() -> Vec<Box<dyn Fn(u32) -> u32>> {
let xs = vec![1_u32, 2, 3];
let mut res: Vec<Box<dyn Fn(u32) -> u32>> = xs.into_iter().map(|x| Box::new(move |y| x + y)).collect();
res
}
fn partially_applied_with_explicit_push() -> Vec<Box<dyn Fn(u32) -> u32>> {
let xs = vec![1_u32, 2, 3];
let mut res = vec![];
for x in xs {
res.push(Box::new(move |y| x + y));
}
res
}
And only this attempt was finally succeeded!
fn partially_applied_with_explicit_push_and_vec_type() -> Vec<Box<dyn Fn(u32) -> u32>> {
let xs = vec![1_u32, 2, 3];
let mut res: Vec<Box<dyn Fn(u32) -> u32>> = vec![];
for x in xs {
res.push(Box::new(move |y| x + y));
}
res
}
Why the type inference is so bad when it comes to dynamic closures?
Why the collect did not work in the first attempts?
Is there a better way to utilize a type inference to express such an idea?