Skip to content

Instantly share code, notes, and snippets.

@itarato
Created January 15, 2025 18:06
Show Gist options
  • Save itarato/24607543e4bd85c92008e068641e45e3 to your computer and use it in GitHub Desktop.
Save itarato/24607543e4bd85c92008e068641e45e3 to your computer and use it in GitHub Desktop.
Map reduce example
struct FooStore {
value: i32,
}
struct ConcreteCompUnit<T> {
unit: T,
}
enum CompUnit<T> {
Concrete(ConcreteCompUnit<T>),
Cluster(Vec<CompUnit<T>>),
}
impl<T> CompUnit<T> {
fn map_reduce<O, MAPFN, REDUCEFN>(&self, map_fn: MAPFN, reduce_fn: REDUCEFN) -> O
where
MAPFN: Fn(&T) -> O + Clone,
REDUCEFN: Fn(Vec<O>) -> O + Clone,
{
let values = match self {
CompUnit::Concrete(concrete_unit) => {
vec![map_fn(&concrete_unit.unit)]
}
CompUnit::Cluster(cluster) => cluster
.iter()
.map(|comp_unit| comp_unit.map_reduce(map_fn.clone(), reduce_fn.clone()))
.collect(),
};
reduce_fn(values)
}
}
fn main() {
let unit = CompUnit::Cluster(vec![
CompUnit::Concrete(ConcreteCompUnit {
unit: FooStore { value: 12 },
}),
CompUnit::Cluster(vec![
CompUnit::Concrete(ConcreteCompUnit {
unit: FooStore { value: 14 },
}),
CompUnit::Concrete(ConcreteCompUnit {
unit: FooStore { value: 16 },
}),
]),
]);
let sum = unit.map_reduce(|foo_store| foo_store.value, |values| values.iter().sum());
println!("Sum: {}", sum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment