macro_rules! try_zip_with {
($vec:expr, $($move:ident)? |$($i:ident),+ $(,)?| $($work:tt)*) => { ... };
}
Expand description
A macro to give syntactic sugar for general_zip::try_zip_with
This allows combining multiple vectors into a one with short-circuiting on the failure case
§Usage
use vec_utils::{zip_with, try_zip_with};
fn to_bits(v: Vec<f32>) -> Vec<u32> {
zip_with!(v, |x| x.to_bits())
}
fn sum_2(v: Vec<f32>, w: Vec<f64>) -> Vec<f64> {
zip_with!((v, w), |x, y| f64::from(x) + y)
}
fn sum_5(a: Vec<i32>, b: Vec<i32>, c: Vec<i32>, d: Vec<i32>, e: Vec<i32>) -> Vec<i32> {
zip_with!((a, b, c, d, e), |a, b, c, d, e| a + b + c + d + e)
}
fn mul_with(a: Vec<i32>) -> Vec<i32> {
zip_with!((a, vec![0, 1, 2, 3, 4, 5, 6, 7]), |a, x| a * x)
}
fn to_bits_no_nans(v: Vec<f32>) -> Result<Vec<u32>, &'static str> {
try_zip_with!(v, |x| if x.is_nan() { Err("Found NaN!") } else { Ok(x.to_bits()) })
}
You can use as many input vectors as you want, just put them all inside the input tuple. Note that the second argument is not a closure, but syntax that looks like a closure, i.e. you can’t make a closure before-hand and pass it as the second argument. Also, you can’t use general patterns in the “closure”’s arguments, only identifiers are allowed. You can specify if you want a move closure by adding the move keyword in from of the “closure”.
use vec_utils::zip_with;
fn add(a: Vec<i32>, b: i32) -> Vec<i32> {
zip_with!(a, move |a| a + b)
}