2 releases

0.1.1 Sep 27, 2024
0.1.0 Jun 26, 2024

#336 in HTTP server

Download history 39/week @ 2024-08-17 44/week @ 2024-08-24 82/week @ 2024-08-31 28/week @ 2024-09-07 52/week @ 2024-09-14 169/week @ 2024-09-21 144/week @ 2024-09-28 34/week @ 2024-10-05 31/week @ 2024-10-12 34/week @ 2024-10-19 45/week @ 2024-10-26 33/week @ 2024-11-02 6/week @ 2024-11-09 29/week @ 2024-11-16 47/week @ 2024-11-23 50/week @ 2024-11-30

133 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