The most abstract function I ever wrote consciously in Rust
Takes 'anything iterable which can be hashed and compared' and return a vector of relative indexes of elements in that iterable.
fn abstract_list<T, G>(input: T) -> Vec<usize>
where
T: Iterator<Item = G>,
G: std::hash::Hash + std::cmp::Eq,
{
let mut dict = HashMap::new();
let mut output = Vec::new();
for elem in input {
let id = dict.len();
output.push(*dict.entry(elem).or_insert(id));
}
output
}
I understand that for guru it's piece of cake, but for me it took a bit of time to trim away all wrong pieces (lifetimes, ref's in the wrong place, etc).
When I got absolutely no excess pieces left, it just clicked. It must be so.
I wrote few tests to check if it really do what I want, but it was exactly one of 'if it compiles, it works' moments. Tests were green on the first run.