Skip to content

Instantly share code, notes, and snippets.

@jaymody
Created November 23, 2021 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaymody/f6d56a2d8143a7c2d0fa9406c3735ab9 to your computer and use it in GitHub Desktop.
Save jaymody/f6d56a2d8143a7c2d0fa9406c3735ab9 to your computer and use it in GitHub Desktop.
map, reduce, filter, forall, count, group_by in Rust
use std::collections::HashMap;
use std::hash::Hash;
fn map<A, B, F>(l: &Vec<A>, f: F) -> Vec<B>
where
F: Fn(&A) -> B,
{
let mut result = Vec::new();
for e in l.iter() {
result.push(f(e));
}
result
}
fn reduce<A, F>(l: &Vec<A>, f: F) -> A
where
A: Clone,
F: Fn(&A, &A) -> A,
{
let mut val: A = l[0].clone();
for e in l.iter().skip(1) {
val = f(&val, e);
}
val
}
fn filter<A, F>(l: &Vec<A>, f: F) -> Vec<A>
where
A: Clone,
F: Fn(&A) -> bool,
{
let mut result = Vec::new();
for e in l.iter() {
if f(e) {
result.push(e.clone());
}
}
result
}
fn forall<A, F>(l: &Vec<A>, f: F) -> bool
where
F: Fn(&A) -> bool,
{
for e in l.iter() {
if !f(e) {
return false;
}
}
return true;
}
fn count<A, F>(l: &Vec<A>, f: F) -> i32
where
F: Fn(&A) -> bool,
{
let mut c: i32 = 0;
for e in l.iter() {
if f(e) {
c += 1;
}
}
c
}
fn group_by<A, K, F>(l: &Vec<A>, f: F) -> HashMap<K, Vec<A>>
where
A: Clone,
K: Eq + Hash,
F: Fn(&A) -> K,
{
let mut m: HashMap<K, Vec<A>> = HashMap::new();
for e in l.iter() {
let k = f(e);
let v = m.entry(k).or_insert(Vec::new());
v.push(e.clone());
}
m
}
fn main() {
/* map */
let lst = vec![1, 2, 3, 4];
let foo = |x: &i32| -> i32 { x * 2 };
println!("{:?}", map(&lst, foo));
/* reduce */
let lst = vec![1, 2, 3, 4];
let foo = |x: &i32, y: &i32| -> i32 { x + y };
println!("{:?}", reduce(&lst, foo));
/* filter */
let lst = vec![1, 2, 3, 4];
let foo = |x: &i32| -> bool { x % 2 == 0 };
println!("{:?}", filter(&lst, foo));
/* forall */
let lst = vec![1, 2, 3, 4];
let foo = |x: &i32| -> bool { x % 2 == 0 };
println!("{:?}", forall(&lst, foo));
let lst = vec![2, 4];
println!("{:?}", forall(&lst, foo));
/* count */
let lst = vec![1, 2, 3, 4, 5];
let foo = |x: &i32| -> bool { x % 2 == 0 };
println!("{:?}", count(&lst, foo));
/* group_by */
let lst = vec![1, 2, 3, 4, 5];
let foo = |x: &i32| -> i32 { x % 2 };
println!("{:?}", group_by(&lst, foo));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment