use std::iter::Iterator; use std::collections::{BTreeMap, btree_map}; // we can use "impl I" when codewars adds rust 1.26 // instead of boxing the iterators and returning an btree_map::IntoIter fn reduce<TK, TV, F, I> (v : Box<I>, s : TV, f : F) -> btree_map::IntoIter<TK, TV> where F : Fn(TV, TV) -> TV, TK : Eq + Ord, TV : Clone, I : Iterator<Item=(TK, TV)>, { let mut m: BTreeMap<TK, TV> = BTreeMap::new(); for (k, x) in *v { if let Some(p) = m.remove(&k) { m.insert(k, f(x, p)); } else { m.insert(k, f(x, s.clone())); } } m.into_iter() }
fn reduce<TK, TV, TS, F>(v : Vec<(TK, TV)>,s : TS,f : F) -> Vec<(TK, TV)>where F : Fn(TS, TV) -> TS {// Codevec![]}- use std::iter::Iterator;
- use std::collections::{BTreeMap, btree_map};
- // we can use "impl I" when codewars adds rust 1.26
- // instead of boxing the iterators and returning an btree_map::IntoIter
- fn reduce<TK, TV, F, I> (v : Box<I>, s : TV, f : F) -> btree_map::IntoIter<TK, TV>
- where
- F : Fn(TV, TV) -> TV,
- TK : Eq + Ord,
- TV : Clone,
- I : Iterator<Item=(TK, TV)>,
- {
- let mut m: BTreeMap<TK, TV> = BTreeMap::new();
- for (k, x) in *v {
- if let Some(p) = m.remove(&k) {
- m.insert(k, f(x, p));
- } else {
- m.insert(k, f(x, s.clone()));
- }
- }
- m.into_iter()
- }
use std::collections::HashSet; #[test] fn returns_summariesed_word_count() { let unreduced = Box::new(vec![("a", 2), ("b", 1), ("a", 1), ("x", 5), ("b", 9)].into_iter()); let reduced = reduce(unreduced, 0, |s, v| s + v); // items in "reduced" are in no particular order, compare using set comparison let reduced_set: HashSet<(&str, i32)> = reduced.collect(); let expected: HashSet<(&str, i32)> = vec![("a", 3), ("b", 10), ("x", 5)].into_iter().collect(); assert_eq!(reduced_set, expected); }
// Rust test example:// TODO: replace with your own tests (TDD), these are just how-to examples.// See: https://doc.rust-lang.org/book/testing.html- use std::collections::HashSet;
- #[test]
- fn returns_summariesed_word_count() {
assert_eq!(reduce(vec![("a", 2), ("b", 1), ("a", 1)],0,|s, v| s + v), vec![("a", 3), ("b", 1)])}- let unreduced = Box::new(vec![("a", 2), ("b", 1), ("a", 1), ("x", 5), ("b", 9)].into_iter());
- let reduced = reduce(unreduced, 0, |s, v| s + v);
- // items in "reduced" are in no particular order, compare using set comparison
- let reduced_set: HashSet<(&str, i32)> = reduced.collect();
- let expected: HashSet<(&str, i32)> = vec![("a", 3), ("b", 10), ("x", 5)].into_iter().collect();
- assert_eq!(reduced_set, expected);
- }