abstalg/
naturals.rs

1// Copyright (C) 2024 Miklos Maroti
2// Licensed under the MIT license (see LICENSE)
3
4use crate::*;
5use num::{BigUint, One, Zero};
6
7/// The commutative monoid of natural numbers (including zero) with arbitrary
8/// large values.
9pub const NN: Naturals = Naturals();
10
11/// The set of natural numbers (including zero) whose elements are
12/// [BigUint](../num/struct.BigUint.html) objects. The semilattice and
13/// commutative semilattice operations are the normal ones while the
14/// lattice order is the normal total order.
15#[derive(Clone, Debug)]
16pub struct Naturals();
17
18impl Domain for Naturals {
19    type Elem = BigUint;
20
21    fn equals(&self, elem1: &Self::Elem, elem2: &Self::Elem) -> bool {
22        elem1 == elem2
23    }
24}
25
26impl Semigroup for Naturals {
27    fn mul(&self, elem1: &Self::Elem, elem2: &Self::Elem) -> Self::Elem {
28        elem1 * elem2
29    }
30}
31
32impl Monoid for Naturals {
33    fn one(&self) -> Self::Elem {
34        One::one()
35    }
36
37    fn is_one(&self, elem: &Self::Elem) -> bool {
38        elem.is_one()
39    }
40
41    fn try_inv(&self, elem: &Self::Elem) -> Option<Self::Elem> {
42        if elem.is_one() {
43            Some(One::one())
44        } else {
45            None
46        }
47    }
48
49    fn invertible(&self, elem: &Self::Elem) -> bool {
50        elem.is_one()
51    }
52}
53
54impl CommuntativeMonoid for Naturals {
55    fn zero(&self) -> Self::Elem {
56        Zero::zero()
57    }
58
59    fn is_zero(&self, elem: &Self::Elem) -> bool {
60        elem.is_zero()
61    }
62
63    fn add(&self, elem1: &Self::Elem, elem2: &Self::Elem) -> Self::Elem {
64        elem1 + elem2
65    }
66
67    fn double(&self, elem: &mut Self::Elem) {
68        *elem *= 2u32;
69    }
70
71    fn times(&self, num: usize, elem: &Self::Elem) -> Self::Elem {
72        num * elem
73    }
74}
75
76impl SemiRing for Naturals {}
77
78impl PartialOrder for Naturals {
79    fn leq(&self, elem1: &Self::Elem, elem2: &Self::Elem) -> bool {
80        elem1 <= elem2
81    }
82}
83
84impl Lattice for Naturals {
85    fn meet(&self, elem1: &Self::Elem, elem2: &Self::Elem) -> Self::Elem {
86        elem1.min(elem2).clone()
87    }
88
89    fn join(&self, elem1: &Self::Elem, elem2: &Self::Elem) -> Self::Elem {
90        elem1.max(elem2).clone()
91    }
92}
93
94impl DistributiveLattice for Naturals {}