relmath-rs 0.7.0

Relation-first mathematics and scientific computing in Rust.
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
//! Deterministic exact binary relation foundations.

use std::collections::BTreeSet;

use crate::{FiniteCarrier, UnaryRelation, traits::FiniteRelation};

/// A finite binary relation.
///
/// The starter implementation stores pairs in a `BTreeSet` so iteration order
/// is deterministic.
///
/// Composition direction is:
///
/// `r.compose(&s)` = `{ (a, c) | exists b. (a, b) in r and (b, c) in s }`
///
/// # Examples
///
/// ```rust
/// use relmath::{BinaryRelation, UnaryRelation};
///
/// let user_role = BinaryRelation::from_pairs([
///     ("ann", "admin"),
///     ("bob", "reviewer"),
/// ]);
///
/// let extra_role = BinaryRelation::from_pairs([
///     ("bob", "reviewer"),
///     ("cara", "guest"),
/// ]);
///
/// let role_permission = BinaryRelation::from_pairs([
///     ("admin", "read"),
///     ("reviewer", "approve"),
///     ("guest", "view"),
/// ]);
///
/// assert_eq!(
///     user_role.union(&extra_role).to_vec(),
///     vec![("ann", "admin"), ("bob", "reviewer"), ("cara", "guest")]
/// );
/// assert_eq!(
///     user_role.intersection(&extra_role).to_vec(),
///     vec![("bob", "reviewer")]
/// );
/// assert_eq!(user_role.difference(&extra_role).to_vec(), vec![("ann", "admin")]);
/// assert_eq!(
///     user_role.converse().to_vec(),
///     vec![("admin", "ann"), ("reviewer", "bob")]
/// );
///
/// let effective_permission = user_role.union(&extra_role).compose(&role_permission);
/// assert!(effective_permission.contains(&"ann", &"read"));
/// assert_eq!(
///     effective_permission.iter().copied().collect::<Vec<_>>(),
///     vec![("ann", "read"), ("bob", "approve"), ("cara", "view")]
/// );
/// assert_eq!(
///     effective_permission.domain().to_vec(),
///     vec!["ann", "bob", "cara"]
/// );
/// assert_eq!(
///     effective_permission.range().to_vec(),
///     vec!["approve", "read", "view"]
/// );
/// assert_eq!(
///     effective_permission
///         .restrict_domain(&UnaryRelation::from_values(["ann", "cara"]))
///         .to_vec(),
///     vec![("ann", "read"), ("cara", "view")]
/// );
/// assert_eq!(
///     effective_permission
///         .restrict_range(&UnaryRelation::from_values(["read", "view"]))
///         .to_vec(),
///     vec![("ann", "read"), ("cara", "view")]
/// );
/// assert_eq!(
///     effective_permission.image(&UnaryRelation::singleton("bob")).to_vec(),
///     vec!["approve"]
/// );
/// assert_eq!(
///     effective_permission
///         .preimage(&UnaryRelation::from_values(["read", "view"]))
///         .to_vec(),
///     vec!["ann", "cara"]
/// );
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BinaryRelation<A: Ord, B: Ord> {
    pairs: BTreeSet<(A, B)>,
}

impl<A: Ord, B: Ord> BinaryRelation<A, B> {
    /// Creates an empty binary relation.
    #[must_use]
    pub fn new() -> Self {
        Self {
            pairs: BTreeSet::new(),
        }
    }

    /// Creates a binary relation from the provided pairs.
    #[must_use]
    pub fn from_pairs<I>(pairs: I) -> Self
    where
        I: IntoIterator<Item = (A, B)>,
    {
        pairs.into_iter().collect()
    }

    /// Inserts a pair into the relation.
    ///
    /// Returns `true` when the pair was not already present.
    pub fn insert(&mut self, left: A, right: B) -> bool {
        self.pairs.insert((left, right))
    }

    /// Returns `true` when the relation contains the given pair.
    #[must_use]
    pub fn contains(&self, left: &A, right: &B) -> bool {
        self.pairs.iter().any(|(candidate_left, candidate_right)| {
            candidate_left == left && candidate_right == right
        })
    }

    /// Returns an iterator over the stored pairs in deterministic order.
    pub fn iter(&self) -> impl Iterator<Item = &(A, B)> {
        self.pairs.iter()
    }

    /// Returns the domain of the relation.
    #[must_use]
    pub fn domain(&self) -> UnaryRelation<A>
    where
        A: Clone,
    {
        self.pairs.iter().map(|(left, _)| left.clone()).collect()
    }

    /// Returns the range of the relation.
    #[must_use]
    pub fn range(&self) -> UnaryRelation<B>
    where
        B: Clone,
    {
        self.pairs.iter().map(|(_, right)| right.clone()).collect()
    }

    /// Returns the converse relation.
    #[must_use]
    pub fn converse(&self) -> BinaryRelation<B, A>
    where
        A: Clone,
        B: Clone,
    {
        self.pairs
            .iter()
            .map(|(left, right)| (right.clone(), left.clone()))
            .collect()
    }

    /// Returns the union of `self` and `other`.
    #[must_use]
    pub fn union(&self, other: &Self) -> Self
    where
        A: Clone,
        B: Clone,
    {
        self.pairs.union(&other.pairs).cloned().collect()
    }

    /// Returns the intersection of `self` and `other`.
    #[must_use]
    pub fn intersection(&self, other: &Self) -> Self
    where
        A: Clone,
        B: Clone,
    {
        self.pairs.intersection(&other.pairs).cloned().collect()
    }

    /// Returns the set difference `self \ other`.
    #[must_use]
    pub fn difference(&self, other: &Self) -> Self
    where
        A: Clone,
        B: Clone,
    {
        self.pairs.difference(&other.pairs).cloned().collect()
    }

    /// Restricts the domain of the relation to `allowed`.
    #[must_use]
    pub fn restrict_domain(&self, allowed: &UnaryRelation<A>) -> Self
    where
        A: Clone,
        B: Clone,
    {
        self.pairs
            .iter()
            .filter(|(left, _)| allowed.contains(left))
            .cloned()
            .collect()
    }

    /// Restricts the range of the relation to `allowed`.
    #[must_use]
    pub fn restrict_range(&self, allowed: &UnaryRelation<B>) -> Self
    where
        A: Clone,
        B: Clone,
    {
        self.pairs
            .iter()
            .filter(|(_, right)| allowed.contains(right))
            .cloned()
            .collect()
    }

    /// Computes the image of `sources` through the relation.
    ///
    /// Returns `{ b | exists a in sources. (a, b) in self }`.
    #[must_use]
    pub fn image(&self, sources: &UnaryRelation<A>) -> UnaryRelation<B>
    where
        B: Clone,
    {
        self.pairs
            .iter()
            .filter(|(left, _)| sources.contains(left))
            .map(|(_, right)| right.clone())
            .collect()
    }

    /// Computes the preimage of `targets` through the relation.
    ///
    /// Returns `{ a | exists b in targets. (a, b) in self }`.
    #[must_use]
    pub fn preimage(&self, targets: &UnaryRelation<B>) -> UnaryRelation<A>
    where
        A: Clone,
    {
        self.pairs
            .iter()
            .filter(|(_, right)| targets.contains(right))
            .map(|(left, _)| left.clone())
            .collect()
    }

    /// Composes `self` with `rhs`.
    ///
    /// The result contains `(a, c)` whenever there exists `b` such that
    /// `(a, b)` is in `self` and `(b, c)` is in `rhs`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::BinaryRelation;
    ///
    /// let user_role = BinaryRelation::from_pairs([
    ///     ("ann", "admin"),
    ///     ("bob", "reviewer"),
    /// ]);
    /// let role_permission = BinaryRelation::from_pairs([
    ///     ("admin", "read"),
    ///     ("reviewer", "approve"),
    /// ]);
    ///
    /// let effective_permission = user_role.compose(&role_permission);
    ///
    /// assert_eq!(
    ///     effective_permission.to_vec(),
    ///     vec![("ann", "read"), ("bob", "approve")]
    /// );
    /// ```
    #[must_use]
    pub fn compose<C>(&self, rhs: &BinaryRelation<B, C>) -> BinaryRelation<A, C>
    where
        A: Clone,
        B: Clone,
        C: Clone + Ord,
    {
        let mut result = BTreeSet::new();

        for (left, middle_left) in &self.pairs {
            for (middle_right, right) in &rhs.pairs {
                if middle_left == middle_right {
                    result.insert((left.clone(), right.clone()));
                }
            }
        }

        BinaryRelation { pairs: result }
    }

    /// Converts the relation into a sorted vector of pairs.
    #[must_use]
    pub fn to_vec(&self) -> Vec<(A, B)>
    where
        A: Clone,
        B: Clone,
    {
        self.pairs.iter().cloned().collect()
    }
}

impl<A: Ord, B: Ord> Default for BinaryRelation<A, B> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Ord> BinaryRelation<T, T> {
    fn identity_from_iter<'a, I>(carrier: I) -> Self
    where
        T: Clone + 'a,
        I: IntoIterator<Item = &'a T>,
    {
        carrier
            .into_iter()
            .map(|value| (value.clone(), value.clone()))
            .collect()
    }

    fn is_reflexive_over<'a, I>(&self, carrier: I) -> bool
    where
        T: 'a,
        I: IntoIterator<Item = &'a T>,
    {
        carrier.into_iter().all(|value| self.contains(value, value))
    }

    fn is_irreflexive_over<'a, I>(&self, carrier: I) -> bool
    where
        T: 'a,
        I: IntoIterator<Item = &'a T>,
    {
        carrier
            .into_iter()
            .all(|value| !self.contains(value, value))
    }

    /// Returns the carrier induced by the relation: domain union range.
    ///
    /// This is support-derived carrier information, not an explicit
    /// [`crate::FiniteCarrier`]. Use [`crate::FiniteCarrier`] when the declared
    /// domain must remain visible even for disconnected values that do not
    /// appear in stored pairs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::{BinaryRelation, FiniteCarrier};
    ///
    /// let step = BinaryRelation::from_pairs([("Draft", "Review")]);
    /// let explicit = FiniteCarrier::from_values(["Draft", "Review", "Archived"]);
    ///
    /// assert_eq!(step.carrier().to_vec(), vec!["Draft", "Review"]);
    /// assert_eq!(explicit.to_vec(), vec!["Archived", "Draft", "Review"]);
    /// ```
    #[must_use]
    pub fn carrier(&self) -> UnaryRelation<T>
    where
        T: Clone,
    {
        self.domain().union(&self.range())
    }

    /// Returns the identity relation on `carrier`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::{BinaryRelation, UnaryRelation};
    ///
    /// let carrier = UnaryRelation::from_values(["Draft", "Review"]);
    ///
    /// assert_eq!(
    ///     BinaryRelation::identity(&carrier).to_vec(),
    ///     vec![("Draft", "Draft"), ("Review", "Review")]
    /// );
    ///
    /// // Use `identity_on` when the carrier should remain explicit.
    /// let explicit = relmath::FiniteCarrier::from_values(["Draft", "Review"]);
    /// assert_eq!(BinaryRelation::identity_on(&explicit).to_vec(), BinaryRelation::identity(&carrier).to_vec());
    /// ```
    #[must_use]
    pub fn identity(carrier: &UnaryRelation<T>) -> Self
    where
        T: Clone,
    {
        Self::identity_from_iter(carrier.iter())
    }

    /// Returns the identity relation on an explicit finite `carrier`.
    ///
    /// This is the G7 carrier-aware companion to [`Self::identity`]. It keeps
    /// the carrier explicit at the API boundary instead of first converting it
    /// into a unary relation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::{BinaryRelation, FiniteCarrier, UnaryRelation};
    ///
    /// let carrier = FiniteCarrier::from_values(["Draft", "Review"]);
    /// let unary = UnaryRelation::from_values(["Draft", "Review"]);
    ///
    /// assert_eq!(
    ///     BinaryRelation::identity_on(&carrier).to_vec(),
    ///     vec![("Draft", "Draft"), ("Review", "Review")]
    /// );
    /// assert_eq!(
    ///     BinaryRelation::identity_on(&carrier).to_vec(),
    ///     BinaryRelation::identity(&unary).to_vec()
    /// );
    /// ```
    #[must_use]
    pub fn identity_on(carrier: &FiniteCarrier<T>) -> Self
    where
        T: Clone,
    {
        Self::identity_from_iter(carrier.iter())
    }

    /// Computes the transitive closure of the relation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::BinaryRelation;
    ///
    /// let step = BinaryRelation::from_pairs([
    ///     ("Draft", "Review"),
    ///     ("Review", "Approved"),
    /// ]);
    ///
    /// assert_eq!(
    ///     step.transitive_closure().to_vec(),
    ///     vec![
    ///         ("Draft", "Approved"),
    ///         ("Draft", "Review"),
    ///         ("Review", "Approved"),
    ///     ]
    /// );
    /// ```
    #[must_use]
    pub fn transitive_closure(&self) -> Self
    where
        T: Clone,
    {
        let mut closure = self.clone();
        let mut changed = true;

        while changed {
            changed = false;
            let snapshot = closure.to_vec();

            for (left, middle_left) in &snapshot {
                for (middle_right, right) in &snapshot {
                    if middle_left == middle_right
                        && closure.pairs.insert((left.clone(), right.clone()))
                    {
                        changed = true;
                    }
                }
            }
        }

        closure
    }

    /// Computes the reflexive-transitive closure on the given `carrier`.
    ///
    /// Values that appear in `carrier` but not in any pair still gain their
    /// identity edge in the result.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::{BinaryRelation, UnaryRelation};
    ///
    /// let step = BinaryRelation::from_pairs([("Draft", "Review")]);
    /// let states = UnaryRelation::from_values(["Draft", "Review", "Archived"]);
    /// let reachable = step.reflexive_transitive_closure(&states);
    ///
    /// assert!(reachable.contains(&"Archived", &"Archived"));
    /// assert!(reachable.contains(&"Draft", &"Review"));
    ///
    /// let explicit_states = relmath::FiniteCarrier::from_values(["Draft", "Review", "Archived"]);
    /// assert_eq!(
    ///     step.reflexive_transitive_closure_on(&explicit_states).to_vec(),
    ///     reachable.to_vec()
    /// );
    /// ```
    #[must_use]
    pub fn reflexive_transitive_closure(&self, carrier: &UnaryRelation<T>) -> Self
    where
        T: Clone,
    {
        self.transitive_closure().union(&Self::identity(carrier))
    }

    /// Computes the reflexive-transitive closure on an explicit finite
    /// `carrier`.
    ///
    /// Values that appear in `carrier` but not in any pair still gain their
    /// identity edge in the result.
    ///
    /// This is the G7 carrier-aware companion to
    /// [`Self::reflexive_transitive_closure`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::{BinaryRelation, FiniteCarrier, UnaryRelation};
    ///
    /// let step = BinaryRelation::from_pairs([("Draft", "Review")]);
    /// let explicit_states = FiniteCarrier::from_values(["Draft", "Review", "Archived"]);
    /// let unary_states = UnaryRelation::from_values(["Draft", "Review", "Archived"]);
    /// let reachable = step.reflexive_transitive_closure_on(&explicit_states);
    ///
    /// assert!(reachable.contains(&"Archived", &"Archived"));
    /// assert!(reachable.contains(&"Draft", &"Review"));
    /// assert_eq!(reachable.to_vec(), step.reflexive_transitive_closure(&unary_states).to_vec());
    /// ```
    #[must_use]
    pub fn reflexive_transitive_closure_on(&self, carrier: &FiniteCarrier<T>) -> Self
    where
        T: Clone,
    {
        self.transitive_closure().union(&Self::identity_on(carrier))
    }

    /// Returns `true` when the relation is reflexive on `carrier`.
    ///
    /// Use [`Self::is_reflexive_on`] when the carrier should remain explicit
    /// as a [`crate::FiniteCarrier`].
    #[must_use]
    pub fn is_reflexive(&self, carrier: &UnaryRelation<T>) -> bool {
        self.is_reflexive_over(carrier.iter())
    }

    /// Returns `true` when the relation is reflexive on an explicit finite
    /// `carrier`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::{BinaryRelation, FiniteCarrier};
    ///
    /// let aliases = BinaryRelation::from_pairs([
    ///     ("A. Smith", "A. Smith"),
    ///     ("A. Smith", "Alice Smith"),
    ///     ("Alice Smith", "A. Smith"),
    ///     ("Alice Smith", "Alice Smith"),
    /// ]);
    /// let carrier = FiniteCarrier::from_values(["A. Smith", "Alice Smith"]);
    ///
    /// assert!(aliases.is_reflexive_on(&carrier));
    /// ```
    #[must_use]
    pub fn is_reflexive_on(&self, carrier: &FiniteCarrier<T>) -> bool {
        self.is_reflexive_over(carrier.iter())
    }

    /// Returns `true` when the relation is irreflexive on `carrier`.
    ///
    /// Use [`Self::is_irreflexive_on`] when the carrier should remain explicit
    /// as a [`crate::FiniteCarrier`].
    #[must_use]
    pub fn is_irreflexive(&self, carrier: &UnaryRelation<T>) -> bool {
        self.is_irreflexive_over(carrier.iter())
    }

    /// Returns `true` when the relation is irreflexive on an explicit finite
    /// `carrier`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::{BinaryRelation, FiniteCarrier};
    ///
    /// let step = BinaryRelation::from_pairs([("Draft", "Review")]);
    /// let carrier = FiniteCarrier::from_values(["Draft", "Review", "Archived"]);
    ///
    /// assert!(step.is_irreflexive_on(&carrier));
    /// ```
    #[must_use]
    pub fn is_irreflexive_on(&self, carrier: &FiniteCarrier<T>) -> bool {
        self.is_irreflexive_over(carrier.iter())
    }

    /// Returns `true` when the relation is symmetric.
    #[must_use]
    pub fn is_symmetric(&self) -> bool {
        self.pairs
            .iter()
            .all(|(left, right)| self.contains(right, left))
    }

    /// Returns `true` when the relation is antisymmetric.
    #[must_use]
    pub fn is_antisymmetric(&self) -> bool {
        self.pairs
            .iter()
            .all(|(left, right)| left == right || !self.contains(right, left))
    }

    /// Returns `true` when the relation is transitive.
    #[must_use]
    pub fn is_transitive(&self) -> bool
    where
        T: Clone,
    {
        let snapshot = self.to_vec();

        snapshot.iter().all(|(left, middle_left)| {
            snapshot.iter().all(|(middle_right, right)| {
                middle_left != middle_right || self.contains(left, right)
            })
        })
    }

    /// Returns `true` when the relation is an equivalence relation on `carrier`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::{BinaryRelation, UnaryRelation};
    ///
    /// let aliases = BinaryRelation::from_pairs([
    ///     ("A. Smith", "A. Smith"),
    ///     ("A. Smith", "Alice Smith"),
    ///     ("Alice Smith", "A. Smith"),
    ///     ("Alice Smith", "Alice Smith"),
    /// ]);
    /// let carrier = UnaryRelation::from_values(["A. Smith", "Alice Smith"]);
    ///
    /// assert!(aliases.is_equivalence(&carrier));
    ///
    /// let explicit = relmath::FiniteCarrier::from_values(["A. Smith", "Alice Smith"]);
    /// assert!(aliases.is_equivalence_on(&explicit));
    /// ```
    #[must_use]
    pub fn is_equivalence(&self, carrier: &UnaryRelation<T>) -> bool
    where
        T: Clone,
    {
        self.is_reflexive(carrier) && self.is_symmetric() && self.is_transitive()
    }

    /// Returns `true` when the relation is an equivalence relation on an
    /// explicit finite `carrier`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::{BinaryRelation, FiniteCarrier};
    ///
    /// let aliases = BinaryRelation::from_pairs([
    ///     ("A. Smith", "A. Smith"),
    ///     ("A. Smith", "Alice Smith"),
    ///     ("Alice Smith", "A. Smith"),
    ///     ("Alice Smith", "Alice Smith"),
    /// ]);
    /// let carrier = FiniteCarrier::from_values(["A. Smith", "Alice Smith"]);
    ///
    /// assert!(aliases.is_equivalence_on(&carrier));
    /// ```
    #[must_use]
    pub fn is_equivalence_on(&self, carrier: &FiniteCarrier<T>) -> bool
    where
        T: Clone,
    {
        self.is_reflexive_on(carrier) && self.is_symmetric() && self.is_transitive()
    }

    /// Returns `true` when the relation is a partial order on `carrier`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::{BinaryRelation, UnaryRelation};
    ///
    /// let divides = BinaryRelation::from_pairs([
    ///     (1_u8, 1_u8),
    ///     (1, 2),
    ///     (1, 4),
    ///     (2, 2),
    ///     (2, 4),
    ///     (4, 4),
    /// ]);
    /// let carrier = UnaryRelation::from_values([1_u8, 2_u8, 4_u8]);
    ///
    /// assert!(divides.is_partial_order(&carrier));
    ///
    /// let explicit = relmath::FiniteCarrier::from_values([1_u8, 2_u8, 4_u8]);
    /// assert!(divides.is_partial_order_on(&explicit));
    /// ```
    #[must_use]
    pub fn is_partial_order(&self, carrier: &UnaryRelation<T>) -> bool
    where
        T: Clone,
    {
        self.is_reflexive(carrier) && self.is_antisymmetric() && self.is_transitive()
    }

    /// Returns `true` when the relation is a partial order on an explicit
    /// finite `carrier`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use relmath::{BinaryRelation, FiniteCarrier};
    ///
    /// let divides = BinaryRelation::from_pairs([
    ///     (1_u8, 1_u8),
    ///     (1, 2),
    ///     (1, 4),
    ///     (2, 2),
    ///     (2, 4),
    ///     (4, 4),
    /// ]);
    /// let carrier = FiniteCarrier::from_values([1_u8, 2_u8, 4_u8]);
    ///
    /// assert!(divides.is_partial_order_on(&carrier));
    /// ```
    #[must_use]
    pub fn is_partial_order_on(&self, carrier: &FiniteCarrier<T>) -> bool
    where
        T: Clone,
    {
        self.is_reflexive_on(carrier) && self.is_antisymmetric() && self.is_transitive()
    }
}

impl<A: Ord, B: Ord> FiniteRelation for BinaryRelation<A, B> {
    fn len(&self) -> usize {
        self.pairs.len()
    }
}

impl<A: Ord, B: Ord> FromIterator<(A, B)> for BinaryRelation<A, B> {
    fn from_iter<I: IntoIterator<Item = (A, B)>>(iter: I) -> Self {
        Self {
            pairs: iter.into_iter().collect(),
        }
    }
}

impl<A: Ord, B: Ord> Extend<(A, B)> for BinaryRelation<A, B> {
    fn extend<I: IntoIterator<Item = (A, B)>>(&mut self, iter: I) {
        self.pairs.extend(iter);
    }
}

impl<A: Ord, B: Ord> IntoIterator for BinaryRelation<A, B> {
    type Item = (A, B);
    type IntoIter = std::collections::btree_set::IntoIter<(A, B)>;

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

impl<'a, A: Ord, B: Ord> IntoIterator for &'a BinaryRelation<A, B> {
    type Item = &'a (A, B);
    type IntoIter = std::collections::btree_set::Iter<'a, (A, B)>;

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