set_theory 1.0.0

A comprehensive mathematical set theory library implementing standard set operations, multisets, and set laws verification
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//! # CustomSet Implementation
//!
//! A mutable mathematical set implementation with unique elements.
//!
//! This is the primary set type in the library, providing full support
//! for all standard set operations with mutable access.

use crate::operations::lazy_ops::PowerSet;
use crate::traits::MathSet;
use std::collections::HashSet;
use std::collections::hash_set;
use std::hash::Hash;
use std::iter::FromIterator;

/// A mathematical set containing unique elements.
///
/// `CustomSet` is the primary mutable set implementation in this library.
/// It follows standard set theory principles where order does not matter
/// and duplicate elements are automatically removed.
///
/// # Type Parameters
///
/// * `T` - The type of elements. Must implement `Eq + Hash + Clone`
///
/// # Examples
///
/// ```rust
/// use set_theory::models::CustomSet;
///
/// // Create from Vec
/// let numbers = CustomSet::from(vec![1, 2, 3, 4]);
///
/// // Create empty set
/// let empty = CustomSet::<i32>::empty();
///
/// // Create from predicate
/// let evens = CustomSet::from_predicate(0..100, |x| x % 2 == 0);
/// ```
///
/// # Performance Characteristics
///
/// | Operation | Complexity |
/// |-----------|------------|
/// | contains | O(1) average |
/// | insert | O(1) average |
/// | remove | O(1) average |
/// | union | O(n + m) |
/// | intersection | O(min(n, m)) |
/// | difference | O(n) |
#[derive(Clone)]
pub struct CustomSet<T: Eq + Hash + Clone> {
    /// Internal storage using HashSet for O(1) lookups
    elements: HashSet<T>,
}

impl<T: Eq + Hash + Clone> CustomSet<T> {
    /// Creates an empty set.
    ///
    /// # Returns
    ///
    /// A new `CustomSet` with no elements.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let empty = CustomSet::<i32>::empty();
    /// assert_eq!(empty.cardinality(), 0);
    /// ```
    pub fn empty() -> Self {
        Self {
            elements: HashSet::new(),
        }
    }

    /// Creates a set from an iterable of elements.
    ///
    /// Duplicate elements are automatically removed.
    ///
    /// # Arguments
    ///
    /// * `iter` - Any iterable collection of elements
    ///
    /// # Returns
    ///
    /// A new `CustomSet` containing unique elements from the iterable.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let set = CustomSet::from(vec![1, 2, 2, 3, 3, 3]);
    /// assert_eq!(set.cardinality(), 3);
    /// ```
    pub fn new<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Self {
            elements: HashSet::from_iter(iter),
        }
    }

    /// Creates a set from a predicate function applied to a universe.
    ///
    /// Only elements from the universe that satisfy the predicate are included.
    ///
    /// # Arguments
    ///
    /// * `universe` - The universe of elements to filter
    /// * `predicate` - Function that returns true for elements to include
    ///
    /// # Returns
    ///
    /// A new `CustomSet` containing elements that satisfy the predicate.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let evens = CustomSet::from_predicate(0..10, |x| x % 2 == 0);
    /// assert_eq!(evens.cardinality(), 5);
    /// assert!(evens.contains(&4));
    /// ```
    pub fn from_predicate<I, F>(universe: I, predicate: F) -> Self
    where
        I: IntoIterator<Item = T>,
        F: Fn(&T) -> bool,
    {
        Self {
            elements: universe.into_iter().filter(|x| predicate(x)).collect(),
        }
    }

    /// Returns the cardinality (number of elements) in the set.
    ///
    /// # Notation
    ///
    /// |A| or n(A)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let set = CustomSet::from(vec![1, 2, 3]);
    /// assert_eq!(set.cardinality(), 3);
    /// ```
    pub fn cardinality(&self) -> usize {
        self.elements.len()
    }

    /// Checks if an element is a member of this set.
    ///
    /// # Notation
    ///
    /// x ∈ A
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let set = CustomSet::from(vec![1, 2, 3]);
    /// assert!(set.contains(&2));
    /// assert!(!set.contains(&5));
    /// ```
    pub fn contains(&self, element: &T) -> bool {
        self.elements.contains(element)
    }

    /// Adds an element to the set.
    ///
    /// If the element already exists, the set remains unchanged.
    ///
    /// # Arguments
    ///
    /// * `element` - The element to add
    ///
    /// # Returns
    ///
    /// `true` if the element was added, `false` if it already existed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let mut set = CustomSet::from(vec![1, 2]);
    /// assert!(set.add(3));
    /// assert!(!set.add(3)); // Already exists
    /// ```
    pub fn add(&mut self, element: T) -> bool {
        self.elements.insert(element)
    }

    /// Removes an element from the set.
    ///
    /// # Arguments
    ///
    /// * `element` - The element to remove
    ///
    /// # Returns
    ///
    /// `true` if the element was removed, `false` if it was not found.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let mut set = CustomSet::from(vec![1, 2, 3]);
    /// assert!(set.remove(&2));
    /// assert!(!set.remove(&2)); // Already removed
    /// ```
    pub fn remove(&mut self, element: &T) -> bool {
        self.elements.remove(element)
    }

    /// Removes all elements from the set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let mut set = CustomSet::from(vec![1, 2, 3]);
    /// set.clear();
    /// assert!(set.is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.elements.clear()
    }

    /// Checks if this set is a subset of another set.
    ///
    /// # Notation
    ///
    /// A ⊆ B
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let a = CustomSet::from(vec![1, 2, 3]);
    /// let b = CustomSet::from(vec![1, 2, 3, 4, 5]);
    /// assert!(a.is_subset_of(&b));
    /// ```
    pub fn is_subset_of(&self, other: &Self) -> bool {
        self.elements.iter().all(|e| other.elements.contains(e))
    }

    /// Checks if this set is a proper subset of another set.
    ///
    /// # Notation
    ///
    /// A ⊂ B
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let a = CustomSet::from(vec![1, 2, 3]);
    /// let b = CustomSet::from(vec![1, 2, 3]);
    /// let c = CustomSet::from(vec![1, 2, 3, 4]);
    /// assert!(!a.is_proper_subset_of(&b));
    /// assert!(a.is_proper_subset_of(&c));
    /// ```
    pub fn is_proper_subset_of(&self, other: &Self) -> bool {
        self.is_subset_of(other) && self.cardinality() < other.cardinality()
    }

    /// Checks if this set is a superset of another set.
    ///
    /// # Notation
    ///
    /// A ⊇ B
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let a = CustomSet::from(vec![1, 2, 3, 4, 5]);
    /// let b = CustomSet::from(vec![1, 2, 3]);
    /// assert!(a.is_superset_of(&b));
    /// ```
    pub fn is_superset_of(&self, other: &Self) -> bool {
        other.is_subset_of(self)
    }

    /// Checks if this set is a proper superset of another set.
    ///
    /// # Notation
    ///
    /// A ⊃ B
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let a = CustomSet::from(vec![1, 2, 3, 4]);
    /// let b = CustomSet::from(vec![1, 2, 3]);
    /// assert!(a.is_proper_superset_of(&b));
    /// ```
    pub fn is_proper_superset_of(&self, other: &Self) -> bool {
        other.is_proper_subset_of(self)
    }

    /// Checks if this set is equal to another set.
    ///
    /// # Notation
    ///
    /// A = B
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let a = CustomSet::from(vec![1, 2, 3]);
    /// let b = CustomSet::from(vec![3, 2, 1]);
    /// assert!(a.equals(&b));
    /// ```
    pub fn equals(&self, other: &Self) -> bool {
        self.cardinality() == other.cardinality() && self.is_subset_of(other)
    }

    /// Checks if this set is equivalent to another set (same cardinality).
    ///
    /// # Notation
    ///
    /// A ~ B
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let a = CustomSet::from(vec![1, 2, 3, 4]);
    /// let b = CustomSet::from(vec!['a', 'b', 'c', 'd']);
    /// assert!(a.is_equivalent_to(&b));
    /// ```
    pub fn is_equivalent_to<U: Eq + Hash + Clone>(&self, other: &CustomSet<U>) -> bool {
        self.cardinality() == other.cardinality()
    }

    /// Checks if this set is disjoint from another set.
    ///
    /// # Notation
    ///
    /// A // B
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let a = CustomSet::from(vec![1, 2, 3]);
    /// let b = CustomSet::from(vec![4, 5, 6]);
    /// assert!(a.is_disjoint_from(&b));
    /// ```
    pub fn is_disjoint_from(&self, other: &Self) -> bool {
        self.elements.iter().all(|e| !other.contains(e))
    }

    /// Returns true if the set contains no elements.
    ///
    /// # Notation
    ///
    /// A = ∅
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let empty = CustomSet::<i32>::empty();
    /// assert!(empty.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }

    /// Returns an iterator over the elements.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let set = CustomSet::from(vec![1, 2, 3]);
    /// for element in set.iter() {
    ///     println!("{}", element);
    /// }
    /// ```
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        self.elements.iter()
    }

    /// Returns the intersection of this set with another.
    ///
    /// # Notation
    ///
    /// A ∩ B = {x | x ∈ A and x ∈ B}
    ///
    /// # Arguments
    ///
    /// * `other` - Reference to the other set
    ///
    /// # Returns
    ///
    /// A new `CustomSet` containing elements present in both sets.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let a = CustomSet::from(vec![2, 4, 6, 8, 10]);
    /// let b = CustomSet::from(vec![4, 10, 14, 18]);
    /// let result = a.intersection(&b);
    /// assert_eq!(result.cardinality(), 2);
    /// ```
    pub fn intersection(&self, other: &Self) -> Self {
        Self {
            elements: self
                .elements
                .intersection(&other.elements)
                .cloned()
                .collect(),
        }
    }

    /// Returns the union of this set with another.
    ///
    /// # Notation
    ///
    /// A ∪ B = {x | x ∈ A or x ∈ B}
    ///
    /// # Arguments
    ///
    /// * `other` - Reference to the other set
    ///
    /// # Returns
    ///
    /// A new `CustomSet` containing all elements from both sets.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let a = CustomSet::from(vec![2, 5, 8]);
    /// let b = CustomSet::from(vec![7, 5, 22]);
    /// let result = a.union(&b);
    /// assert_eq!(result.cardinality(), 5);
    /// ```
    pub fn union(&self, other: &Self) -> Self {
        CustomSet {
            elements: self.elements.union(&other.elements).cloned().collect(),
        }
    }

    /// Returns the complement of this set with respect to a universal set.
    ///
    /// # Notation
    ///
    /// A' = {x | x ∈ U and x ∉ A}
    ///
    /// # Arguments
    ///
    /// * `universal` - Reference to the universal set
    ///
    /// # Returns
    ///
    /// A new `CustomSet` containing elements in universal but not in this set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let universal = CustomSet::from(vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
    /// let a = CustomSet::from(vec![1, 3, 7, 9]);
    /// let result = a.complement(&universal);
    /// assert_eq!(result.cardinality(), 5);
    /// ```
    pub fn complement(&self, universal: &Self) -> Self {
        Self {
            elements: universal
                .elements
                .iter()
                .filter(|e| !self.elements.contains(*e))
                .cloned()
                .collect(),
        }
    }

    ///
    /// # Notation
    ///
    /// A - B = {x | x ∈ A and x ∉ B}
    ///
    /// # Arguments
    ///
    /// * `other` - Reference to the other set
    ///
    /// # Returns
    ///
    /// A new `CustomSet` containing elements in this set but not in other.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let a = CustomSet::from(vec![1, 2, 3, 4, 5]);
    /// let b = CustomSet::from(vec![2, 4]);
    /// let result = a.difference(&b);
    /// assert_eq!(result.cardinality(), 3);
    /// ```
    pub fn difference(&self, other: &Self) -> Self {
        Self {
            elements: self
                .elements
                .iter()
                .filter(|e| !other.elements.contains(*e))
                .cloned()
                .collect(),
        }
    }

    /// Returns the symmetric difference of this set with another.
    ///
    /// # Notation
    ///
    /// A ⊕ B = (A ∪ B) - (A ∩ B)
    ///
    /// # Arguments
    ///
    /// * `other` - Reference to the other set
    ///
    /// # Returns
    ///
    /// A new `CustomSet` containing elements in either set but not both.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let a = CustomSet::from(vec![2, 4, 6]);
    /// let b = CustomSet::from(vec![2, 3, 5]);
    /// let result = a.symmetric_difference(&b);
    /// assert_eq!(result.cardinality(), 4);
    /// ```
    pub fn symmetric_difference(&self, other: &Self) -> Self {
        self.union(other).difference(&self.intersection(other))
    }

    /// Returns the power set of this set (lazy evaluation).
    ///
    /// # Notation
    ///
    /// P(A) or 2^A
    ///
    /// # Returns
    ///
    /// A `PowerSet` iterator that yields subsets one by one.
    ///
    /// # Performance Note
    ///
    /// For a set with n elements, the power set contains 2^n subsets.
    /// This method uses lazy evaluation to avoid memory explosion.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let a = CustomSet::from(vec![1, 2]);
    /// let power_set: Vec<_> = a.power_set().collect();
    /// assert_eq!(power_set.len(), 4); // 2^2 = 4
    /// ```
    pub fn power_set(&self) -> PowerSet<T> {
        PowerSet::new(self)
    }
}

// Implement MathSet trait
impl<T: Eq + Hash + Clone> MathSet<T> for CustomSet<T> {
    fn cardinality(&self) -> usize {
        self.cardinality()
    }

    fn contains(&self, element: &T) -> bool {
        self.contains(element)
    }

    fn is_subset_of(&self, other: &Self) -> bool {
        self.is_subset_of(other)
    }

    fn is_proper_subset_of(&self, other: &Self) -> bool {
        self.is_proper_subset_of(other)
    }

    fn equals(&self, other: &Self) -> bool {
        self.equals(other)
    }

    fn is_disjoint_from(&self, other: &Self) -> bool {
        self.is_disjoint_from(other)
    }

    fn is_empty(&self) -> bool {
        self.is_empty()
    }
}

// Implement FromIterator
impl<T: Eq + Hash + Clone> FromIterator<T> for CustomSet<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        CustomSet::new(iter)
    }
}

// Implement IntoIterator
impl<T: Eq + Hash + Clone> IntoIterator for CustomSet<T> {
    type Item = T;
    type IntoIter = hash_set::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.elements.into_iter()
    }
}

// Implement From<Vec<T>>
impl<T: Eq + Hash + Clone> From<Vec<T>> for CustomSet<T> {
    /// Creates a CustomSet from a Vec.
    ///
    /// # Arguments
    ///
    /// * `vec` - A vector of elements to create the set from
    ///
    /// # Returns
    ///
    /// A new `CustomSet` containing unique elements from the vector.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use set_theory::models::CustomSet;
    ///
    /// let set = CustomSet::from(vec![1, 2, 3]);
    /// assert_eq!(set.cardinality(), 3);
    /// ```
    fn from(vec: Vec<T>) -> Self {
        CustomSet::new(vec)
    }
}

// Implement From<&[T]>
impl<T: Eq + Hash + Clone> From<&[T]> for CustomSet<T> {
    fn from(slice: &[T]) -> Self {
        CustomSet::new(slice.iter().cloned())
    }
}

// Implement Display
impl<T: Eq + Hash + Clone + std::fmt::Display> std::fmt::Display for CustomSet<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.is_empty() {
            write!(f, "")
        } else {
            let elements: Vec<_> = self.elements.iter().collect();
            write!(
                f,
                "{{{}}}",
                elements
                    .iter()
                    .map(|e| e.to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        }
    }
}

// Implement Debug
impl<T: Eq + Hash + Clone + std::fmt::Debug> std::fmt::Debug for CustomSet<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "CustomSet({:?})", self.elements)
    }
}

// Implement PartialEq
impl<T: Eq + Hash + Clone> PartialEq for CustomSet<T> {
    fn eq(&self, other: &Self) -> bool {
        self.equals(other)
    }
}

// Implement Eq
impl<T: Eq + Hash + Clone> Eq for CustomSet<T> {}

// Implement Hash
impl<T: Eq + Hash + Clone + std::fmt::Debug> std::hash::Hash for CustomSet<T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        let mut elements: Vec<_> = self.elements.iter().collect();
        elements.sort_by(|a, b| format!("{:?}", a).cmp(&format!("{:?}", b)));
        for element in elements {
            element.hash(state);
        }
    }
}