2 releases

0.1.1 Sep 27, 2024
0.1.0 Jun 26, 2024

#4 in #algebraic

Download history 22/week @ 2024-06-28 20/week @ 2024-07-05 33/week @ 2024-07-12 14/week @ 2024-07-19 15/week @ 2024-08-09 50/week @ 2024-08-16 44/week @ 2024-08-23 69/week @ 2024-08-30 40/week @ 2024-09-06 52/week @ 2024-09-13 59/week @ 2024-09-20 248/week @ 2024-09-27 39/week @ 2024-10-04 30/week @ 2024-10-11

388 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