2 releases

0.1.1 Sep 27, 2024
0.1.0 Jun 26, 2024

#328 in HTTP server

Download history 26/week @ 2024-08-11 39/week @ 2024-08-18 62/week @ 2024-08-25 65/week @ 2024-09-01 37/week @ 2024-09-08 54/week @ 2024-09-15 192/week @ 2024-09-22 125/week @ 2024-09-29 19/week @ 2024-10-06 31/week @ 2024-10-13 34/week @ 2024-10-20 45/week @ 2024-10-27 35/week @ 2024-11-03

146 downloads per month
Used in 23 crates (2 directly)

Apache-2.0

12KB
128 lines

Algebraic traits

A selection of traits representing abstract algebras. These can be used to abstract over types that have differing concepts of 'combination'.

Examples

Consider the following function to combine maps:

use std::hash::Hash;
use std::collections::{HashMap, HashSet};

use swimos_algebra::Semigroup;

fn combine_maps<K: Eq + Hash + Clone, T: Semigroup>(
    mut left: HashMap<K, T>,
    mut right: HashMap<K, T>) -> HashMap<K, T> {
   
    let keys = left.keys().chain(right.keys()).cloned().collect::<HashSet<_>>();

    keys.into_iter().filter_map(|k| {
        match (left.remove(&k), right.remove(&k)) {
           (None, Some(r)) => Some((k, r)),
           (Some(l), None) => Some((k, l)),
           (Some(l), Some(r)) => Some((k, Semigroup::op(l, r))),
           _ => None,
       }
    }).collect()
}

This can be applied to a map with integer values,

#
#
#
let left_ints = [("red", 3), ("green", 23), ("blue", 1)]
    .into_iter()
    .collect::<HashMap<_, _>>();

let right_ints = [("red", 4), ("blue", 1)]
    .into_iter()
    .collect::<HashMap<_, _>>();

let expected_ints = [("red", 7), ("green", 23), ("blue", 2)]
    .into_iter()
    .collect::<HashMap<_, _>>();

assert_eq!(combine_maps(left_ints, right_ints), expected_ints);

or a map with vectors as values:

#
#
#
let left_vecs = [
    ("red", vec![12, -5, 6]),
    ("green", vec![1]),
    ("blue", vec![5, 8, 11]),
]
.into_iter()
.collect::<HashMap<_, _>>();

let right_vecs = [
    ("red", vec![4, 1]),
    ("blue", vec![-7])
]
.into_iter()
.collect::<HashMap<_, _>>();

let expected_vecs = [
    ("red", vec![12, -5, 6, 4, 1]),
    ("green", vec![1]),
    ("blue", vec![5, 8, 11, -7]),
]
.into_iter()
.collect::<HashMap<_, _>>();

assert_eq!(combine_maps(left_vecs, right_vecs), expected_vecs);

No runtime deps