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 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 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 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()
}
}
#[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));
}
}