I am trying to write a naif implementation of kmeans in Rust for learning purposes. One of the steps is as follows: I have a collection of points xs
and another collection of points centroids
. I want to group the xs
based on the nearest neighbour among the centroids. That is, two points belong to the same group if they have a common nearest neighbour.
For instance in Scala this would look like
xs groupBy { x => closest(x, centroids) } values
Not finding a groupBy
method in the standard library, I tried to write it like follows (assume Point
and closest
are defined):
fn clusters(xs: & Vec<Point>, centroids: & Vec<Point>) -> Vec<Vec<Point>> {
let mut groups: TreeMap<Point, Vec<Point>> = TreeMap::new();
// for x in xs.iter() {
// let y = closest(*x, centroids);
// match groups.find(&y) {
// Some(mut val) => val.push(*x),
// None => {
// groups.insert(y, vec![*x]);
// },
// }
// }
let result: Vec<Vec<Point>> = groups.values().map(|x| *x).collect();
result
}
I have commented the central part, because I already have problems creating a TreeMap<Point, Vec<Point>>
and returning its values as a Vec<Vec<Point>>
. There is a method values
on TreeMap, which returns an iterator of type Map<...>
. I have tried:
- returning the iterator directly, but Rust complains that then I have to add a lifetime specifier and I am not sure which one to use
- collect it into a
Vec
. The problem is that the elements of the iterator are actually pointers toVec<Point>
, so I have to do something likelet result: Vec<& Vec<Point>> = groups.values().collect();
. Again, Rust will not let me return those pointers, because they live too short - dereferencing all those pointers, like the above. I think this is the right way to go, but Rust tells me
error: cannot move out of dereference of &-pointer
What is the correct way to return the values of that map?
Also, if I decomment the central part, Rust prevents me from doing groups.insert(y, vec![*x]);
because groups
is locally borrowed as an immutable reference in the pattern matching. How would I go fixing this?