Entrywise mapping for nested structs and tuples
ā Rust š 2025-10-15 š¤ surdeus šļø 10I 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
š·ļø Rust_feed