Entrywise mapping for nested structs and tuples

āš“ Rust    šŸ“… 2025-10-15    šŸ‘¤ surdeus    šŸ‘ļø 2      

surdeus

I have code that constructs various nested data structures, such as (Vec<Vec<T>>, Vec<T>).

Given a function T -> U, I’d like to map all elements entrywise and obtain a corresponding instance of (Vec<Vec<U>>, Vec<U>). Conceptually, this feels completely straightforward from a functorial perspective, but I’m unsure what the cleanest Rust pattern is for expressing it.

The only approach I can think of is defining a trait like this:

pub trait EntrywiseMapping {
    type Inner;
    type Output<U>: EntrywiseMapping<Inner = U>;

    fn map<U, F>(self, f: F) -> Self::Output<U>
    where
        F: Fn(Self::Inner) -> U;
}

Then I could implement it for T, Vec<T>, and potentially use a procedural macro to derive it for more complex structs.

However, this feels a bit heavy-handed, and moreover the trait itself does not really enforce entrywise mapping — is there a more idiomatic or lightweight way to achieve entrywise mapping across nested containers or custom structs in Rust?

1 post - 1 participant

Read full topic

šŸ·ļø Rust_feed