Recursive macros

⚓ Rust    📅 2025-07-24    👤 surdeus    👁️ 1      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Recursive macros

Is there a way to do this in Rust? Are recursive macros the answer? (Depth can be bounded if necessary.)

scaled_add(x,y,c) (or something like x.scaled_add(y,c) ) should return x + c*y if x,y are both of some type called F (which is a field). If instead x and y are Vec<F>, then do this elementwise and return a Vec<F>. If they are Vec<Vec<F>>, then return another Vec<Vec<F>>, etc.

So for this one could write:

pub trait ScaledAdd {
    fn scaled_add(self, other: &Self, c: &F) -> Self;
}

impl ScaledAdd for F {
    fn scaled_add(self, other: &Self, c: &F) -> Self {
        self + c * other
    }
}

macro_rules! impl_scaled_add_for_vec {
    ($t:ty) => {
        impl ScaledAdd for Vec<$t> {
            fn scaled_add(self, other: &Self, c: &F) -> Self {
                self.into_iter()
                    .zip(other.into_iter())
                    .map(|(a,b)| a.scaled_add(b, c))
                    .collect()
            }
        }
    }
}

But now what if x and y are of type (F, Vec<F>)? Or (F, &Vec<F>)? Is there a simple way to handle this?

4 posts - 2 participants

Read full topic

🏷️ Rust_feed