use std::collections::HashMap;
use std::hash::Hash;
pub trait List<T> {
fn map<'a, U>(&'a self, f: impl FnMut(&'a T) -> U) -> Vec<U>
where
T: 'a;
fn filter_map<'a, U>(&'a self, f: impl FnMut(&'a T) -> Option<U>) -> Vec<U>
where
T: 'a;
fn filter(&self, keep: impl FnMut(&T) -> bool) -> Vec<T>
where
T: Clone;
fn matching(&self, keep: impl FnMut(&T) -> bool) -> Vec<&T>;
fn reject(&self, mut drop: impl FnMut(&T) -> bool) -> Vec<T>
where
T: Clone,
{
self.filter(|item| !drop(item))
}
fn find(&self, matches: impl FnMut(&T) -> bool) -> Option<&T>;
fn any(&self, matches: impl FnMut(&T) -> bool) -> bool;
fn all(&self, matches: impl FnMut(&T) -> bool) -> bool;
fn count_where(&self, matches: impl FnMut(&T) -> bool) -> usize;
fn sum<N: std::iter::Sum<N>>(&self, f: impl FnMut(&T) -> N) -> N;
fn sorted_by<K: Ord>(&self, key: impl FnMut(&T) -> K) -> Vec<T>
where
T: Clone;
fn min_by_key<K: Ord>(&self, key: impl FnMut(&T) -> K) -> Option<&T>;
fn max_by_key<K: Ord>(&self, key: impl FnMut(&T) -> K) -> Option<&T>;
fn group_by<K: Eq + Hash + Clone>(&self, key: impl FnMut(&T) -> K) -> Vec<(K, Vec<T>)>
where
T: Clone;
fn uniq_by<K: Eq + Hash>(&self, key: impl FnMut(&T) -> K) -> Vec<T>
where
T: Clone;
fn each(&self, f: impl FnMut(&T));
fn try_map<'a, U, E>(&'a self, f: impl FnMut(&'a T) -> Result<U, E>) -> Result<Vec<U>, E>
where
T: 'a;
fn find_map<'a, U>(&'a self, f: impl FnMut(&'a T) -> Option<U>) -> Option<U>
where
T: 'a;
fn position(&self, matches: impl FnMut(&T) -> bool) -> Option<usize>;
fn enumerate(&self) -> Vec<(usize, &T)>;
fn zip<'a, U>(&'a self, other: &'a [U]) -> Vec<(&'a T, &'a U)>;
fn partition(&self, keep: impl FnMut(&T) -> bool) -> (Vec<T>, Vec<T>)
where
T: Clone;
fn index_by<K: Eq + Hash>(&self, key: impl FnMut(&T) -> K) -> HashMap<K, T>
where
T: Clone;
fn count_by<K: Eq + Hash + Clone>(&self, key: impl FnMut(&T) -> K) -> Vec<(K, usize)>;
fn chunked(&self, size: usize) -> Vec<Vec<T>>
where
T: Clone;
fn sliding(&self, size: usize) -> Vec<Vec<T>>
where
T: Clone;
fn minimum<K: Ord>(&self, f: impl FnMut(&T) -> K) -> Option<K>;
fn maximum<K: Ord>(&self, f: impl FnMut(&T) -> K) -> Option<K>;
fn average<N: crate::values::ToF>(&self, f: impl FnMut(&T) -> N) -> Option<f64>;
fn reversed(&self) -> Vec<T>
where
T: Clone;
}
pub trait Compact<T> {
fn compact(&self) -> Vec<T>;
}
impl<T: Clone> Compact<T> for [Option<T>] {
fn compact(&self) -> Vec<T> {
self.iter().flatten().cloned().collect()
}
}
impl<T> List<T> for [T] {
fn map<'a, U>(&'a self, f: impl FnMut(&'a T) -> U) -> Vec<U>
where
T: 'a,
{
self.iter().map(f).collect()
}
fn filter_map<'a, U>(&'a self, f: impl FnMut(&'a T) -> Option<U>) -> Vec<U>
where
T: 'a,
{
self.iter().filter_map(f).collect()
}
fn filter(&self, mut keep: impl FnMut(&T) -> bool) -> Vec<T>
where
T: Clone,
{
self.iter().filter(|item| keep(item)).cloned().collect()
}
fn matching(&self, mut keep: impl FnMut(&T) -> bool) -> Vec<&T> {
self.iter().filter(|item| keep(item)).collect()
}
fn find(&self, mut matches: impl FnMut(&T) -> bool) -> Option<&T> {
self.iter().find(|item| matches(item))
}
fn any(&self, matches: impl FnMut(&T) -> bool) -> bool {
self.iter().any(matches)
}
fn all(&self, matches: impl FnMut(&T) -> bool) -> bool {
self.iter().all(matches)
}
fn count_where(&self, mut matches: impl FnMut(&T) -> bool) -> usize {
self.iter().filter(|item| matches(item)).count()
}
fn sum<N: std::iter::Sum<N>>(&self, f: impl FnMut(&T) -> N) -> N {
self.iter().map(f).sum()
}
fn sorted_by<K: Ord>(&self, mut key: impl FnMut(&T) -> K) -> Vec<T>
where
T: Clone,
{
let mut sorted = self.to_vec();
sorted.sort_by_key(|item| key(item));
sorted
}
fn min_by_key<K: Ord>(&self, mut key: impl FnMut(&T) -> K) -> Option<&T> {
self.iter().min_by_key(|item| key(item))
}
fn max_by_key<K: Ord>(&self, mut key: impl FnMut(&T) -> K) -> Option<&T> {
self.iter().max_by_key(|item| key(item))
}
fn group_by<K: Eq + Hash + Clone>(&self, mut key: impl FnMut(&T) -> K) -> Vec<(K, Vec<T>)>
where
T: Clone,
{
let mut groups: Vec<(K, Vec<T>)> = Vec::new();
let mut at: HashMap<K, usize> = HashMap::new();
for item in self {
let k = key(item);
match at.get(&k) {
Some(&i) => groups[i].1.push(item.clone()),
None => {
at.insert(k.clone(), groups.len());
groups.push((k, vec![item.clone()]));
}
}
}
groups
}
fn uniq_by<K: Eq + Hash>(&self, mut key: impl FnMut(&T) -> K) -> Vec<T>
where
T: Clone,
{
let mut seen = std::collections::HashSet::new();
self.iter()
.filter(|item| seen.insert(key(item)))
.cloned()
.collect()
}
fn try_map<'a, U, E>(&'a self, f: impl FnMut(&'a T) -> Result<U, E>) -> Result<Vec<U>, E>
where
T: 'a,
{
self.iter().map(f).collect()
}
fn each(&self, f: impl FnMut(&T)) {
self.iter().for_each(f);
}
fn find_map<'a, U>(&'a self, f: impl FnMut(&'a T) -> Option<U>) -> Option<U>
where
T: 'a,
{
self.iter().find_map(f)
}
fn position(&self, matches: impl FnMut(&T) -> bool) -> Option<usize> {
self.iter().position(matches)
}
fn enumerate(&self) -> Vec<(usize, &T)> {
self.iter().enumerate().collect()
}
fn zip<'a, U>(&'a self, other: &'a [U]) -> Vec<(&'a T, &'a U)> {
self.iter().zip(other).collect()
}
fn reversed(&self) -> Vec<T>
where
T: Clone,
{
self.iter().rev().cloned().collect()
}
fn partition(&self, mut keep: impl FnMut(&T) -> bool) -> (Vec<T>, Vec<T>)
where
T: Clone,
{
let mut yes = Vec::new();
let mut no = Vec::new();
for item in self {
if keep(item) {
yes.push(item.clone());
} else {
no.push(item.clone());
}
}
(yes, no)
}
fn index_by<K: Eq + Hash>(&self, mut key: impl FnMut(&T) -> K) -> HashMap<K, T>
where
T: Clone,
{
self.iter().map(|item| (key(item), item.clone())).collect()
}
fn count_by<K: Eq + Hash + Clone>(&self, mut key: impl FnMut(&T) -> K) -> Vec<(K, usize)> {
let mut counts: Vec<(K, usize)> = Vec::new();
let mut at: HashMap<K, usize> = HashMap::new();
for item in self {
let k = key(item);
match at.get(&k) {
Some(&i) => counts[i].1 += 1,
None => {
at.insert(k.clone(), counts.len());
counts.push((k, 1));
}
}
}
counts
}
fn chunked(&self, size: usize) -> Vec<Vec<T>>
where
T: Clone,
{
self.chunks(size.max(1)).map(<[T]>::to_vec).collect()
}
fn sliding(&self, size: usize) -> Vec<Vec<T>>
where
T: Clone,
{
self.windows(size.max(1)).map(<[T]>::to_vec).collect()
}
fn minimum<K: Ord>(&self, f: impl FnMut(&T) -> K) -> Option<K> {
self.iter().map(f).min()
}
fn maximum<K: Ord>(&self, f: impl FnMut(&T) -> K) -> Option<K> {
self.iter().map(f).max()
}
fn average<N: crate::values::ToF>(&self, mut f: impl FnMut(&T) -> N) -> Option<f64> {
if self.is_empty() {
return None;
}
let total: f64 = self.iter().map(|item| f(item).to_f()).sum();
Some(total / self.len() as f64)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lists_read_as_ruby_and_elixir_do() {
let words: &[&str] = &["pear", "fig", "apple", "plum"];
assert_eq!(words.map(|w| w.len()), vec![4, 3, 5, 4]);
assert_eq!(words.reject(|w| w.len() == 4), vec!["fig", "apple"]);
assert_eq!(
words.filter_map(|w| w.strip_prefix('p')),
vec!["ear", "lum"]
);
assert!(words.any(|w| w.starts_with('a')));
assert!(!words.all(|w| w.len() > 3));
assert_eq!(words.count_where(|w| w.len() == 4), 2);
assert_eq!(
words.sorted_by(|w| w.len()),
vec!["fig", "pear", "plum", "apple"]
);
assert_eq!(words.min_by_key(|w| w.len()), Some(&"fig"));
assert_eq!(
words.group_by(|w| w.len()),
vec![
(4, vec!["pear", "plum"]),
(3, vec!["fig"]),
(5, vec!["apple"])
]
);
assert_eq!(words.uniq_by(|w| w.len()), vec!["pear", "fig", "apple"]);
let lengths: Result<Vec<usize>, String> = words.try_map(|w| Ok(w.len()));
assert_eq!(lengths, Ok(vec![4, 3, 5, 4]));
let failed: Result<Vec<usize>, String> = words.try_map(|w| {
if w.len() > 4 {
Err(w.to_string())
} else {
Ok(1)
}
});
assert_eq!(failed, Err("apple".to_owned()));
assert_eq!([Some(1), None, Some(3)].compact(), vec![1, 3]);
assert_eq!(words.find_map(|w| w.strip_prefix('a')), Some("pple"));
assert_eq!(words.position(|w| w.len() == 5), Some(2));
assert_eq!(words.enumerate()[1], (1, &"fig"));
assert_eq!(words.zip(&[1, 2]), vec![(&"pear", &1), (&"fig", &2)]);
assert_eq!(words.reversed(), vec!["plum", "apple", "fig", "pear"]);
let owned: Vec<i32> = Vec::from([3, 1, 2]);
assert_eq!(owned.position(|n| *n == 1), Some(1));
let numbers = [1, 2, 3, 4, 5];
assert_eq!(
numbers.partition(|n| n % 2 == 0),
(vec![2, 4], vec![1, 3, 5])
);
assert_eq!(words.index_by(|w| w.len())[&3], "fig");
assert_eq!(words.count_by(|w| w.len()), vec![(4, 2), (3, 1), (5, 1)]);
assert_eq!(numbers.chunked(2), vec![vec![1, 2], vec![3, 4], vec![5]]);
assert_eq!(numbers[..3].sliding(2), vec![vec![1, 2], vec![2, 3]]);
assert_eq!(words.minimum(|w| w.len()), Some(3));
assert_eq!(words.maximum(|w| w.len()), Some(5));
assert_eq!(numbers.average(|n| *n), Some(3.0));
assert_eq!(Vec::<i32>::new().average(|n| *n), None);
}
}