1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use crate::common::*;
pub trait Flatten {
type Output;
fn flatten(self) -> Self::Output;
}
impl<T> Flatten for Vec<Vec<T>> {
type Output = Vec<T>;
fn flatten(self) -> Self::Output {
self.into_iter().flatten().collect()
}
}
impl<T> Flatten for Vec<Option<T>> {
type Output = Vec<T>;
fn flatten(self) -> Self::Output {
self.into_iter().flatten().collect()
}
}
impl<K, L, V> Flatten for HashMap<K, HashMap<L, V>>
where
K: Eq + Hash + Clone,
L: Eq + Hash,
{
type Output = HashMap<(K, L), V>;
fn flatten(self) -> Self::Output {
self.into_iter()
.flat_map(|(k1, map)| {
map.into_iter()
.map(move |(k2, val)| ((k1.clone(), k2), val))
})
.collect()
}
}
impl<K, V> Flatten for HashMap<K, Vec<V>>
where
K: Eq + Hash + Clone,
{
type Output = HashMap<(K, usize), V>;
fn flatten(self) -> Self::Output {
self.into_iter()
.flat_map(|(key, vec)| {
vec.into_iter()
.enumerate()
.map(move |(index, value)| ((key.clone(), index), value))
})
.collect()
}
}
impl<K, V> Flatten for Vec<HashMap<K, V>>
where
K: Eq + Hash + Clone,
{
type Output = HashMap<(usize, K), V>;
fn flatten(self) -> Self::Output {
self.into_iter()
.enumerate()
.flat_map(|(index, map)| {
map.into_iter()
.map(move |(key, value)| ((index, key), value))
})
.collect()
}
}