oat_rust 0.2.0

User-friendly tools for applied topology
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
//! Partial and total orders
//! 
//! See also [`indexing_and_bijection`](crate::utilities::indexing_and_bijection).
//! 
//! Rust offers two traits to compare the order of elements: [PartialOrd] and [Ord]. For example, if you want to know if
//! `a` is less than `b`, you can run
//! 
//! ```
//! let a = 0; 
//! let b = 1;
//! 
//! // This will assign a value of `true` to `is_less`.
//! let is_less =   a.lt(&b);
//! ```
//! 
//! However, [PartialOrd] and [Ord] offer limited flexibility,
//! especially in situations where multiple different orders might apply to the same type of object (for example, we might want to
//! sort simplices according to dimension, diameter, or lexicographic order, or some combination of the three).
//! 
//! To provide greater flexibility, OAT provides two similar but different traits, [`JudgePartialOrder`] and [`JudgeOrder`].
//! The functions defined by these traits are similar to [PartialOrd] and [Ord], with one important difference: rather than
//! compare to objects directly, you define a third object which performs the comparison for you.
//! 
//! ```
//! use oat_rust::utilities::order::{OrderOperatorAuto, OrderOperatorAutoReverse};
//! use oat_rust::utilities::order::JudgePartialOrder;
//! 
//! // Define a and b
//! let a = 0;
//! let b = 1;
//! 
//! // Define an order operator:
//! // this one impelements the default order on objects
//! let order_operator = OrderOperatorAuto;
//! 
//! // Use the order operator to compare a and b
//! assert!( order_operator.judge_lt( &a, &b ) );
//! 
//! // Define a DIFFERENT order operator
//! let order_operator_reverse = OrderOperatorAutoReverse;
//! 
//! // Use the new operator to compare a and b with a DIFFERENT order:
//! // this particular operator happens to reverse the default order on objects,
//! // so it will assert that b is less than a
//! assert!( order_operator_reverse.judge_lt( &b, &a ) );
//! ```
//! 
//! This gives greater
//! flexibility, since you can define many different order operators to compare elements of the same type.
//! 
//! # Terminology
//! 
//! We call an object that implements [JudgePartialOrder] and/or [JudgeOrder] an **order operator**.
//! It is analogous to the idea of a [RingOperator](crate::algebra::rings), in the sense that you use
//! order operators to get order information about other objects, just like you use ring operators to get
//! algebraic information about other structures.
//! 
//! # Design notes
//! 
//! In many situations [OrderOperatorAuto] is this simplest to use.  [OrderOperatorByKey] is also common for comparing vector entries; it has a smaller type signature than [OrderOperatorByKeyCustom], but for many operations, e.g. [U-match factorization](crate::algebra::matrices::operations::umatch), the larger signature allows users to pass customized order operators.
// //! object that "externalizes" that implements traits for
// //! comparing two elements -- traits such as [`JudgePartialOrder`], [`ComparePartialOrder`], and [`CompareOrder`].
// //! 
// //! Order plays an important role in the OAT for several reasons.  Some examples include
// //!
// //!   - it is easier to to write a lazy iterator for the sum of two sparse vectors (represented as lists of nonzero entires) if the lists are already sorted.
// //!   - min-heaps rely on order comparisons to function
// //!
// //! Often we find that a single application requires us to order a set of elements in one way at one time, and another way at another time.
// //! 
// //! To achieve this without changing the type of elements being ordered, we use a "helper" object that implements traits for
// //! comparing two elements -- traits such as [`JudgePartialOrder`], [`ComparePartialOrder`], and [`CompareOrder`].


use std::cmp::Ordering;


//  ---------------------------------------------------------------------------
//  SORTING
//  ---------------------------------------------------------------------------

//  SEE ALSO: the sequences_and_ordinals module
//  -------------------------------------------


/// Returns true iff `order_operator.judge_lt( a, b ) == true` for every consequtive pair of
/// elements `a`, `b`, in the slice.  Returns `true` by default for slices of length `<= 1`.
/// 
/// # Examples
/// 
/// ```
/// use oat_rust::utilities::order::{ is_sorted_strictly, OrderOperatorAuto };
/// 
/// assert!( is_sorted_strictly(   &vec![ 0, 1, 2], & OrderOperatorAuto ) );
/// assert!( ! is_sorted_strictly( &vec![ 0, 1, 1], & OrderOperatorAuto ) );
/// ```
pub fn is_sorted_strictly < T, OrderOperator, > ( data: &[T], order_operator: & OrderOperator ) -> bool
    where OrderOperator: JudgePartialOrder<  T >,
{
    data.windows(2).all(|w| order_operator.judge_lt( &w[0], &w[1]) )
}



//  ---------------------------------------------------------------------------
//  ORDER OPERATOR TRAITS
//  ---------------------------------------------------------------------------


//  JudgePartialOrder + JudgeOrder
//  ---------------------------------------------------------------------------


/// Modeled off the Rust trait `std::cmp::PartialOrd`.
/// 
/// It is commonly the case that multiple *different* partial orders are
/// relevant to struct.  For example, one might want to order simplices in
/// ascending/descending lexicographic order, or first by dimension and second
/// by lexicographic order, etc.  The Rust traits for `Ord` and `PartialOrd`
/// only accomodate a single order per struct.  Therefore we create third-party
/// objects or "operators" to operationalize different orders.
/// 
///  REMARK: This trait is similar to (and extends) one copied from the itertools 
///  library for `kmerge`.  The OAT developers
///  suspect that the trait was introduced in order to supply type information 
///  that ordinary closures might miss.  At least, we tried removing the trait
///  from the IteratorsMergedInSortedOrder code we adapted from Itertools, and ran into some type 
///  erros at compilation.
/// 
/// # Examples
/// 
/// For general information about order operators see the documentation page for [order](crate::utilities::order).
/// 
/// The following example shows how to implement [JudgePartialOrder] on a new struct in order to make a new order operator.
/// 
/// ```
/// use oat_rust::utilities::order::{JudgeOrder, JudgePartialOrder};
/// use std::cmp::Ordering;
/// 
/// //  Define a new type of struct
/// //  ---------------------------        
/// pub struct MyOrderOperator;
/// 
/// //  Implement the JudgePartialOrder trait on our new struct
/// //  -------------------------------------------------------
/// impl JudgePartialOrder< usize > for MyOrderOperator {
/// 
///     // this function should return true iff left >= right
///     fn judge_ge(&self,left: &usize, right: &usize) -> bool {
///         left >= right 
///     }
///     // this function should return true iff left > right
///     fn judge_gt(&self,left: &usize, right: &usize) -> bool {
///         left > right
///     }
///     // this function should return true iff left <= right
///     fn judge_le(&self,left: &usize, right: &usize) -> bool {
///         left <= right
///     }
///     // this function should return true iff left < right
///     fn judge_lt(&self, left: &usize, right: &usize ) -> bool {
///         left < right
///     }
///     fn judge_partial_cmp( & self, left: & usize, right: & usize )  -> Option<Ordering> {
///         Some( left.cmp( right ) )
///     }
/// }
/// 
/// //  Implement the JudgeOrder trait on our new struct
/// //  ------------------------------------------------
/// impl JudgeOrder< usize > for MyOrderOperator {
///     // the judge_clamp function in OAT is modeled off of the clamp function here: https://doc.rust-lang.org/std/cmp/trait.Ord.html
///     fn judge_clamp(&self, clampee: usize, min: usize, max: usize) -> usize {
///         clampee.clamp(min,max) // here we just use Rust's built-in clamp function
///     }
///     // the judge_cmp function in OAT is modeled off of the clamp function here: https://doc.rust-lang.org/std/cmp/trait.Ord.html            
///     fn judge_cmp(&self, left: &usize, right: &usize ) -> Ordering {
///         left.cmp(right)
///     }
///     // should return the maximum of left and right
///     fn judge_max(&self, left: usize, right: usize) -> usize {
///         left.max(right)
///     }
///     // should return the minimum of left and right
///     fn judge_min(&self, left: usize, right: usize) -> usize {
///         left.min(right)
///     }
/// }
/// 
/// //  Use the trait
/// fn compare_order() {
///     let a = 1usize;
///     let b = 2usize;
///     let order_operator = MyOrderOperator;
/// 
///     if order_operator.judge_lt( &a, &b ) { println!("a is strictly less than b") }
///     else { println!("a is greater than or equal to b")}
/// }
/// ```
pub trait JudgePartialOrder< T > {
    /// Similar to the `.cmp` method in `std::cmp::PartialOrd`
    fn judge_partial_cmp
        ( & self, left: & T, right: & T ) 
        -> 
        Option<Ordering>;    
    // {
    //     let is_le = self.le(left, right);
    //     let is_ge = self.ge(left, right);
    //     if is_le {
    //         if is_ge { Some( Ordering::Equal ) }
    //         else { Some( Ordering::Less ) }
    //     }
    //     else {
    //         if is_ge { Some( Ordering::Greater ) }
    //         else { None }
    //     }
    // }
    /// Returns true iff left < right
    fn judge_lt(&self, left: &T, right: &T ) -> bool { self.judge_partial_cmp(left, right) == Some(Ordering::Less) }// { self.le( left, right ) && ! self.ge( left, right ) }
    /// Returns true iff left ≤ right    
    fn judge_le(&self,left: &T, right: &T) -> bool { match self.judge_partial_cmp(left,right){ Some(Ordering::Less) => true, Some(Ordering::Equal) => true, _ => false } }
    /// Returns true iff left > right    
    fn judge_gt(&self,left: &T, right: &T) -> bool { self.judge_partial_cmp(left, right) == Some(Ordering::Greater) } // { self.judge_lt( right, left ) }
    /// Returns true iff left ≥ right    
    fn judge_ge(&self,left: &T, right: &T) -> bool { match self.judge_partial_cmp(left,right){ Some(Ordering::Greater) => true, Some(Ordering::Equal) => true, _ => false } }

    /// Returns the reverse order operator
    fn reverse_order_judgements( self ) -> ReverseOrder< Self > 
        where Self: Sized
    {
        ReverseOrder::new( self )
    }
}

/// Modeled off the Rust trait `std::cmp::Ord`.
/// 
/// It is commonly the case that multiple *different* partial orders are
/// relevant to struct.  For example, one might want to order simplices in
/// ascending/descending lexicographic order, or first by dimension and second
/// by lexicographic order, etc.  The Rust traits for `Ord` and `PartialOrd`
/// only accomodate a single order per struct.  Therefore we create third-party
/// objects or "operators" to operationalize different orders.
/// 
/// # Examples
/// 
/// For general information about order operators see the documentation page for [order](crate::utilities::order).
/// 
/// The following example shows how to implement [JudgePartialOrder] on a new struct in order to make a new order operator.
/// 
/// ```
/// use oat_rust::utilities::order::{JudgePartialOrder, JudgeOrder};
/// 
/// use std::cmp::Ordering;
/// 
/// //  Define a new type of struct
/// //  ---------------------------        
/// pub struct MyOrderOperator;
/// 
/// //  Implement the JudgePartialOrder trait on our new struct
/// //  -------------------------------------------------------
/// impl JudgePartialOrder< usize > for MyOrderOperator {
/// 
///     // this function should return true iff left >= right
///     fn judge_ge(&self,left: &usize, right: &usize) -> bool {
///         left >= right 
///     }
///     // this function should return true iff left > right
///     fn judge_gt(&self,left: &usize, right: &usize) -> bool {
///         left > right
///     }
///     // this function should return true iff left <= right
///     fn judge_le(&self,left: &usize, right: &usize) -> bool {
///         left <= right
///     }
///     // this function should return true iff left < right
///     fn judge_lt(&self, left: &usize, right: &usize ) -> bool {
///         left < right
///     }
///     fn judge_partial_cmp( & self, left: & usize, right: & usize )  -> Option<Ordering> {
///         Some( left.cmp( right ) )
///     }
/// }
/// 
/// //  Implement the JudgeOrder trait on our new struct
/// //  ------------------------------------------------
/// impl JudgeOrder< usize > for MyOrderOperator {
///     // the judge_clamp function in OAT is modeled off of the clamp function here: https://doc.rust-lang.org/std/cmp/trait.Ord.html
///     fn judge_clamp(&self, clampee: usize, min: usize, max: usize) -> usize {
///         clampee.clamp(min,max) // here we just use Rust's built-in clamp function
///     }
///     // the judge_cmp function in OAT is modeled off of the clamp function here: https://doc.rust-lang.org/std/cmp/trait.Ord.html            
///     fn judge_cmp(&self, left: &usize, right: &usize ) -> Ordering {
///         left.cmp(right)
///     }
///     // should return the maximum of left and right
///     fn judge_max(&self, left: usize, right: usize) -> usize {
///         left.max(right)
///     }
///     // should return the minimum of left and right
///     fn judge_min(&self, left: usize, right: usize) -> usize {
///         left.min(right)
///     }
/// }
/// 
/// //  Use the trait
/// fn compare_order() {
///     let a = 1usize;
///     let b = 2usize;
///     let order_operator = MyOrderOperator;
/// 
///     if order_operator.judge_lt( &a, &b ) { println!("a is strictly less than b") }
///     else { println!("a is greater than or equal to b")}
/// }
/// ```
pub trait JudgeOrder< T > : JudgePartialOrder< T > 
{
    /// Similar to the `.cmp` method in `std::cmp::Ord`
    fn judge_cmp(&self, left: &T, right: &T ) -> Ordering {
        self.judge_partial_cmp(left, right).unwrap()
    }
    /// Return the greater of left, right; if they are equal, reutrh left
    fn judge_max(&self, left: T, right: T) -> T { match self.judge_lt(&left, &right) { true => { right }, false => { left } } }
    /// Return the lesser of left, rhx; if they are equal, return left
    fn judge_min(&self, left: T, right: T) -> T { match self.judge_le(&left, &right) { true => { left }, false => { right } } }
    /// Similar to Rust's `num::clamp`    
    fn judge_clamp(&self, clampee: T, min: T, max: T) -> T { 
        if self.judge_lt( &max, &min ) { panic!("Cannot call `self.clamp( clampee, min, max )` when max < min") };

        if self.judge_lt( &clampee, &min ) { min }
        else if self.judge_lt( &max, &clampee ) { return max }
        else { return clampee }
    }
}


//  ---------------------------------------------------------------------------
//  NONE GREATER
//  ---------------------------------------------------------------------------


/// Wrapper for `Option<T>`; implements `Ord` and `PartialOrd`, where `None` is the greatest (as opposed to the least) element
/// 
/// Compare this with `Option<T>`, where `None` is the least element
/// 
/// # Example
/// 
/// ```
/// use oat_rust::utilities::order::MakeNoneMaximum;
/// use std::cmp::Ordering;
/// 
/// let a   =   MakeNoneMaximum::from_val(0usize);
/// let b   =   MakeNoneMaximum::from_val(1usize);
/// let c   =   MakeNoneMaximum::from_opt(None);
/// 
/// assert!( a <  b );
/// assert!( a == a );
/// assert!( a <  c );
/// assert!( c == c );
/// 
/// 
/// assert_eq!( a.partial_cmp(&a), Some(Ordering::Equal) );
/// assert_eq!( a.partial_cmp(&b), Some(Ordering::Less ) );
/// assert_eq!( a.partial_cmp(&c), Some(Ordering::Less ) );
/// assert_eq!( c.partial_cmp(&c), Some(Ordering::Equal) );
/// 
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MakeNoneMaximum< T > { pub opt: Option< T > }

impl < T > MakeNoneMaximum< T > {
    pub fn new( opt: Option<T> ) -> Self { MakeNoneMaximum{opt} }    
    
    /// Wraps `opt` in a `MakeNoneMaximum{ opt }` struct
    pub fn from_opt( opt: Option<T> ) -> Self { MakeNoneMaximum{opt} }

    /// Wraps `val` in a `MakeNoneMaximum{ opt: Some(val) }` struct
    pub fn from_val( val: T ) -> Self{ MakeNoneMaximum{ opt: Some(val) } }

    /// Returns a clone of the value wrapped in `MakeNoneMaximum`, if it exists
    /// 
    /// # Panics
    /// 
    /// Panics if `self.opt` is `None`
    pub fn val( &self ) -> T where T: Clone { self.opt.clone().unwrap() }

    /// Returns the internally stored `Option<T>`
    pub fn into_inner( self ) -> Option<T> { self.opt }
}

impl < T: Ord + PartialOrd + Eq > Ord for MakeNoneMaximum< T > {
    

    fn cmp(&self, other: &Self) -> Ordering {
        match (&self.opt, &other.opt) {
            (Some(a),Some(b)) => { a.cmp(b) }            
            (None,   None   ) => { Ordering::Equal   }
            (None,   Some(_)) => { Ordering::Greater }
            (Some(_),None   ) => { Ordering::Less    }             
        }
        // match self.opt {
        //     Some( self_val ) => {
        //         match other {
        //             Some( other_val ) => {

        //             }
        //         }
        //     }
        // }
    }
}

impl < T: Ord + PartialOrd > PartialOrd for MakeNoneMaximum< T > {
    
    /// ```
    /// use oat_rust::utilities::order::MakeNoneMaximum;
    /// 
    /// let a   =   MakeNoneMaximum::from_val(0usize);
    /// let b   =   MakeNoneMaximum::from_val(1usize);
    /// let c   =   MakeNoneMaximum::from_opt(None);
    /// 
    /// assert!( a <  b );
    /// assert!( a == a );
    /// assert!( a <  c );
    /// assert!( c == c );
    /// 
    /// ```
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (&self.opt, &other.opt) {
            (Some(a),Some(b)) => { a.partial_cmp(b) }            
            (None,   None   ) => { Some(Ordering::Equal  ) }
            (None,   Some(_)) => { Some(Ordering::Greater) }
            (Some(_),None   ) => { Some(Ordering::Less   ) }            
        }        
    }
}



//  ---------------------------------------------------------------------------
//  DEFAULT IMPLEMENTATION ON REFERENCES
//  ---------------------------------------------------------------------------



//  Auto-implement on references
//  ----------------------------

impl < 'a, T, OrderOperator: JudgePartialOrder< T > >

    JudgePartialOrder< T > for
    
    &'a OrderOperator
{
    fn judge_partial_cmp
        ( & self, left: & T, right: & T ) -> Option<Ordering> { (*self).judge_partial_cmp(left, right) }
}


//  Auto-implement on references
//  ----------------------------

impl < 'a, T, OrderOperator: JudgeOrder< T > >

    JudgeOrder< T > for
    
    &'a OrderOperator
{
    fn judge_cmp(&self, left: &T, right: &T ) -> Ordering {
        (*self).judge_cmp(left, right)
    }
}






//  ---------------------------------------------------------------------------
//  IMPLEMENTORS OF `JudgeOrder`
//  ---------------------------------------------------------------------------

//  WORKS FINE, BUT WE HAVE RESTURCTURED THE ORDER OPERATOR TRAITS, AND THIS STRUCT NO LONGER PROVIDES MUCH FUNCTIONALITY; OK TO DELETE

// /// Wrapper around any struct `ComparatorJudgePartialOrder` that implements the trait `JudgePartialOrder`; the wrapper then implements `JudgePartialOrder` and `JudgeOrder`.
// /// 
// /// # Examples
// /// 
// /// ```
// /// use oat_rust::utilities::order::{InferTotalOrderFromJudgePartialOrder, OrderOperatorAuto, JudgePartialOrder, JudgeOrder};
// /// 
// /// let order_operator      =   InferTotalOrderFromJudgePartialOrder::new( OrderOperatorAuto );
// /// assert_eq!( order_operator.le( &2, &2), true );
// /// assert_eq!( order_operator.judge_lt( &2, &2), false);
// /// assert_eq!( order_operator.le( &1, &2), true );
// /// assert_eq!( order_operator.judge_lt( &1, &2), true );
// /// assert_eq!( order_operator.le( &2, &1), false);
// /// assert_eq!( order_operator.judge_lt( &2, &1), false);
// /// ```
// #[derive(Clone, Copy, Debug, Eq, PartialEq)]
// pub struct InferTotalOrderFromJudgePartialOrder
//             < ComparatorJudgePartialOrder >
//             { comparator_lt: ComparatorJudgePartialOrder }

// impl < ComparatorJudgePartialOrder > 

//     InferTotalOrderFromJudgePartialOrder
//         < ComparatorJudgePartialOrder > 
// {
//     pub fn new( comparator_lt: ComparatorJudgePartialOrder ) -> InferTotalOrderFromJudgePartialOrder< ComparatorJudgePartialOrder > 
//         { InferTotalOrderFromJudgePartialOrder{ comparator_lt  } }
// }

// impl < ComparatorJudgePartialOrder, T > 

//     JudgePartialOrder
//         < T > for
//     InferTotalOrderFromJudgePartialOrder
//         < ComparatorJudgePartialOrder >

//     where 
//         ComparatorJudgePartialOrder:     JudgePartialOrder< T >,
// {
//     fn le(&self,left: &T, right: &T) -> bool { ! self.comparator_lt.judge_lt(right, left) }
//     fn lt(&self,left: &T, right: &T) -> bool { self.comparator_lt.judge_lt(left, right) }  
// }

// impl < ComparatorJudgePartialOrder, T > 

//     JudgeOrder
//         < T > for
//     InferTotalOrderFromJudgePartialOrder
//         < ComparatorJudgePartialOrder >

//     where 
//         ComparatorJudgePartialOrder:     JudgePartialOrder< T >,
// {}


//  ---------------------------------------------------------------------------
//  IMPLEMENTORS OF `JudgePartialOrder`
//  ---------------------------------------------------------------------------










//  Merged type
//  -------------


/// A type that can be either of two different order operators, `OrderOperator1` or `OrderOperator2`.
/// 
/// This enum will judge the order of elements according to whichever order operator it contains internally.
/// 
/// # Examples
/// 
/// ```
/// use oat_rust::utilities::order::{ ReverseOrder, OrderOperatorAuto, TwoTypeOrderOperator, JudgePartialOrder };
/// 
/// // a function to get either a forward or reverse order operator
/// let get_forward_operator = |forward| {
///     if forward { 
///         TwoTypeOrderOperator::Version1( OrderOperatorAuto ) 
///     } else { 
///         TwoTypeOrderOperator::Version2( ReverseOrder::new( OrderOperatorAuto ) )
///     }
/// };
/// 
/// // get some operators
/// let forward = get_forward_operator( true );
/// let reverse = get_forward_operator( false );
/// 
/// // check that they order elements correctly
/// assert!( forward.judge_lt( &1, &2) );
/// assert!( reverse.judge_lt( &2, &1) );
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum TwoTypeOrderOperator< OrderOperator1, OrderOperator2 >
{
    Version1( OrderOperator1 ),
    Version2( OrderOperator2 ),
}


impl < OrderOperator1, OrderOperator2, T > 

    JudgePartialOrder
        < T > for 
        
    TwoTypeOrderOperator
        < OrderOperator1, OrderOperator2 >

where 
    OrderOperator1: JudgePartialOrder< T >,
    OrderOperator2: JudgePartialOrder< T >,
{
    fn judge_partial_cmp( & self, left: & T, right: & T ) -> Option<Ordering> {
        match self {
            TwoTypeOrderOperator::Version1( op ) => op.judge_partial_cmp( left, right ),
            TwoTypeOrderOperator::Version2( op ) => op.judge_partial_cmp( left, right ),
        }
    }
}




impl < OrderOperator1, OrderOperator2, T > 

    JudgeOrder
        < T > for 
        
    TwoTypeOrderOperator
        < OrderOperator1, OrderOperator2 >

where 
    OrderOperator1: JudgeOrder< T >,
    OrderOperator2: JudgeOrder< T >,
{
    fn judge_cmp( & self, left: & T, right: & T ) -> Ordering {
        match self {
            TwoTypeOrderOperator::Version1( op ) => op.judge_cmp( left, right ),
            TwoTypeOrderOperator::Version2( op ) => op.judge_cmp( left, right ),
        }
    }
}















//  Reverse order
//  -------------

/// Represents the reverse of a total order
/// 
/// # Examples
/// 
/// ```
/// use oat_rust::utilities::order::{ ReverseOrder, OrderOperatorAuto, JudgePartialOrder };
/// 
/// let mut order_operator_reverse = ReverseOrder::new( OrderOperatorAuto );
/// assert!( order_operator_reverse.judge_lt( &2, &1) )
/// ```
/// 
/// # See also
/// 
/// See See the documentation for the [order](crate::utilities::order) module for an overview on order operators.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ReverseOrder
            < UnreversedOrderOperator > 
{ unreversed_order_operator: UnreversedOrderOperator }

impl < UnreversedOrderOperator > 

    ReverseOrder
        < UnreversedOrderOperator > 
{ 
    pub fn new( unreversed_order_operator: UnreversedOrderOperator ) ->  ReverseOrder< UnreversedOrderOperator > { ReverseOrder{ unreversed_order_operator } }
}

impl < T, UnreversedOrderOperator: JudgePartialOrder< T > > 

    JudgePartialOrder
        < T > for 

    ReverseOrder
        < UnreversedOrderOperator >

{
    fn judge_partial_cmp( & self, left: & T, right: & T ) -> Option<Ordering> { self.unreversed_order_operator.judge_partial_cmp( right, left ) }
}

impl < T, UnreversedOrderOperator: JudgePartialOrder< T > + JudgeOrder< T > > 

    JudgeOrder
        < T > for 

    ReverseOrder
        < UnreversedOrderOperator >

{
    fn judge_cmp( & self, left: & T, right: & T ) -> Ordering { self.unreversed_order_operator.judge_cmp( right, left ) }
}

/// A convenience trait which allows the user to reverse an order operator via `operator.reverse_order()`
pub trait IntoReverseOrder 
    where Self: Sized
{
    /// Returns an inverted order operator, consuming `self`
    fn into_reverse_order( self ) -> ReverseOrder< Self > { ReverseOrder::new(self) } // for reasons I don't understand, this auto-implementation doesn't seem to work, but the implementation directly below seems to do the trick
}

impl < T: Sized> IntoReverseOrder for T 
{
    /// Returns an inverted order operator, consuming `self`
    fn into_reverse_order( self ) -> ReverseOrder< Self > { ReverseOrder::new(self) }  
}


//  Less-than (auto implementor, any type)
//  ----------------------------

/// Applies the default order to any object that has a default order
/// 
/// That is, you can use this struct to compare the order of `a` and `b`, whenever
/// `a` and `b` implement [PartialOrd]
/// or [Ord]; 
/// 
/// This struct uses zero memory.
/// 
/// # See also
/// 
/// See See the documentation for the [order](crate::utilities::order) module for an overview on order operators.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, Ord, PartialOrd)]
pub struct OrderOperatorAuto;

impl OrderOperatorAuto {
    pub fn new() -> OrderOperatorAuto { OrderOperatorAuto }
}

impl<T: PartialOrd> JudgePartialOrder< T > for OrderOperatorAuto {
    
    fn judge_partial_cmp
            ( & self, left: & T, right: & T ) 
            -> 
            Option<Ordering> {
        left.partial_cmp( right )
    }
}

impl<T: Ord> 

    JudgeOrder
        < T > for 
        
    OrderOperatorAuto {} // all methods in this trait are auto-implemented



//  Greater-than (auto implementor)
//  -------------------------------

/// Applies the REVERSE of the default order to any object that has a default order
/// 
/// If `a < b`, then this struct will say that `b < a`.
/// 
/// You can use this struct to compare the order of `a` and `b`, whenever
/// `a` and `b` implement [PartialOrd]
/// or [Ord].
/// 
/// This struct uses zero memory.
/// 
/// # See also
/// 
/// See See the documentation for the [order](crate::utilities::order) module for an overview on order operators.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct OrderOperatorAutoReverse;

impl OrderOperatorAutoReverse {
    pub fn new() -> OrderOperatorAutoReverse { OrderOperatorAutoReverse }
}

impl<T: PartialOrd> JudgePartialOrder< T > for OrderOperatorAutoReverse {
    fn judge_partial_cmp
            ( & self, left: & T, right: & T ) 
            -> 
            Option<Ordering> {
        right.partial_cmp(left)
    }
}

impl<T: Ord> JudgeOrder< T > for OrderOperatorAutoReverse {} // all methods in this trait are auto-implemented



//  Less-than-by-key (auto implementor)
//  -----------------------------------

/// Determines the order of key-value pairs according to their keys
/// 
/// You can use this struct to compare elements of type `T`, whenever 
/// - `T` implements [`KeyValGet<Key, Val>`](`KeyValGet`), and
/// - `Key` implements [PartialOrd] or [Ord]
/// 
/// This struct will indicate that `x < y` whenever `x.key() < y.key()`
/// 
/// # See also
/// 
/// See See the documentation for the [order](crate::utilities::order) module for an overview on order operators.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Copy, new, Serialize, Deserialize)]
pub struct OrderOperatorByKey;

    

// JudgePartialOrder
impl < KeyValuePairStruct >

    JudgePartialOrder 
        < KeyValuePairStruct > for 
    
    OrderOperatorByKey 

    where   KeyValuePairStruct::Key:      PartialOrd,
            KeyValuePairStruct:           KeyValGet,
    
    {

    fn judge_partial_cmp
            ( & self, left: & KeyValuePairStruct, right: & KeyValuePairStruct ) 
            -> 
            Option<Ordering> {
        ( left.key() ).partial_cmp( &right.key() )
    }
}

// JudgeOrder
impl< KeyValuePairStruct >

    JudgeOrder 
        < KeyValuePairStruct > for 
    
    OrderOperatorByKey 

    where   KeyValuePairStruct::Key:      Ord,
            KeyValuePairStruct:           KeyValGet,
    
    {

    fn judge_cmp
            ( & self, left: & KeyValuePairStruct, right: & KeyValuePairStruct ) 
            -> 
            Ordering {
        ( left.key() ).cmp( &right.key() )
    }
}


//  Less-than-by-key (auto implementor for 2-tuples)
//  -----------------------------------


/// Determines the order of key-value pairs of type `(Key,Val)` according to `Key`
/// 
/// You can use this struct to compare elements of type `(Key,Val)`, whenever `Key` implements
/// [PartialOrd] or [Ord].
/// 
/// This struct will indicate that `(a,x) < (b,y)` whenever `a < b`. It is a little less general
/// than `OrderOperatorByKey`, but it may be more efficient. This is because `OrderOperatorByKey`
/// will clone the first entry of a tuple each time it makes a comparison, whereas `OrderOperatorByKeyTuple`
/// will only make a reference.
/// 
/// This struct uses zero memory.
/// 
/// # See also
/// 
/// See See the documentation for the [order](crate::utilities::order) module for an overview on order operators.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Copy, new)]
pub struct OrderOperatorByKeyTuple;



// JudgePartialOrder
impl< Key, Val >

    JudgePartialOrder 
        < (Key, Val) > for 
    
    OrderOperatorByKeyTuple //< Key, Val >

    where   
        Key:            PartialOrd,
    {
    fn judge_partial_cmp
            ( & self, left: & (Key, Val), right: & (Key, Val) ) 
            -> 
            Option<Ordering> {
        left.0.partial_cmp( &right.0)
    }
}

// JudgeOrder
impl< Key, Val >

    JudgeOrder 
        < (Key, Val) > for 
    
    OrderOperatorByKeyTuple 

    where Key:          Ord,
    
    {

    fn judge_cmp
            ( & self, left: & (Key, Val), right: & (Key, Val) ) 
            -> 
            Ordering {
        ( left.0 ).cmp( &right.0 )
    }
}


//  Greater-than-by-key (auto implementor)
//  --------------------------------------


/// Determines the order of key-value pairs according to their keys (but reversed!)
/// 
/// You can use this struct to compare elements of type `T`, whenever 
/// - `T` implements [`KeyValGet<Key, Val>`](`KeyValGet`), and
/// - `Key` implements [PartialOrd] or [Ord]
/// 
/// This struct will indicate that `x < y` whenever `x.key() > y.key()`
/// 
/// # See also
/// 
/// See See the documentation for the [order](crate::utilities::order) module for an overview on order operators.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Copy, new)]
pub struct OrderOperatorByKeyReverse;


// JudgePartialOrder
impl< KeyValuePairStruct >

    JudgePartialOrder 
        < KeyValuePairStruct >
    
    for OrderOperatorByKeyReverse 

    where   KeyValuePairStruct::Key:      PartialOrd,
            KeyValuePairStruct:           KeyValGet,
    
    {

    fn judge_partial_cmp
            ( & self, left: & KeyValuePairStruct, right: & KeyValuePairStruct ) 
            -> 
            Option<Ordering> {
        right.key().partial_cmp( &left.key() )
    }
}

// JudgeOrder
impl< KeyValuePairStruct >

    JudgeOrder 
        < KeyValuePairStruct >
    
    for OrderOperatorByKeyReverse 

    where   KeyValuePairStruct::Key:      Ord,
            KeyValuePairStruct:           KeyValGet,
    
    {

    fn judge_cmp
            ( & self, left: & KeyValuePairStruct, right: & KeyValuePairStruct ) 
            -> 
            Ordering {
        ( right.key() ).cmp( &left.key() )
    }
}



//  Less-than-by-key-WITH-custom-comparator (auto implementor)
//  --------------------------------------


/// Determines the order of key-value pairs by applying a custom order operator to keys.
/// 
/// This struct is a wrapper around a customized order operator, which the user can provide.
/// The struct will indicate that `(a,x) < (b,y)` whenever the order operator says that `a < b`.
/// 
/// Any object can be treated as a key-value pair as long as it implements [`KeyValGet<Key, Val>`](`KeyValGet`).
/// 
/// # See also
/// 
/// See See the documentation for the [order](crate::utilities::order) module for an overview on order operators.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Copy, new)]
pub struct OrderOperatorByKeyCustom < OrderOperatorForKeys > 
{
    order_operator_for_keys: OrderOperatorForKeys,    
}


// JudgePartialOrder
impl< KeyValuePairStruct, OrderOperatorForKeys >

    JudgePartialOrder 
        < KeyValuePairStruct > for 
    
    OrderOperatorByKeyCustom 
        < OrderOperatorForKeys > 
        
    where
        KeyValuePairStruct:         KeyValGet,
        OrderOperatorForKeys:       JudgePartialOrder <  KeyValuePairStruct::Key >,
    
    {
    fn judge_partial_cmp
            ( & self, left: & KeyValuePairStruct, right: & KeyValuePairStruct ) 
            -> 
            Option<Ordering> {
        self.order_operator_for_keys.judge_partial_cmp( & left.key(), & right.key())
    }
}

// JudgeOrder
impl< KeyValuePairStruct, OrderOperatorForKeys >

    JudgeOrder 
        < KeyValuePairStruct > for 
    
    OrderOperatorByKeyCustom 
        < OrderOperatorForKeys > 
        
    where
        KeyValuePairStruct:         KeyValGet,
        OrderOperatorForKeys:       JudgeOrder <  KeyValuePairStruct::Key >,
    {}


//  Mutable closure 
//  ---------------------------------------------

use std::marker::PhantomData;

use derive_new::new;
use serde::{Deserialize, Serialize};

use crate::algebra::vectors::entries::KeyValGet;


/// Determines order based on a user-supplied funcion that returns `Option<Ordering>`
/// 
/// Concretely, this is a wrapper for objects that implement `FnMut(&T, &T)->Option<Ordering>`.
/// If `x` is such an object, then we say `a < b` if `x( &a, &b ) = Some(Ordering::Less)`.
/// 
/// # See also
/// 
/// See See the documentation for the [order](crate::utilities::order) module for an overview on order operators.
#[derive(Debug, Eq, PartialEq)]
pub struct OrderOperatorByFn
                < F: Fn(&T, &T)->Option<Ordering>, T > 
{ 
    order_operator_unwrapped:         F, 
    phantom_comparatee:               PhantomData< T > 
}


// Constructor
impl < F: Fn(&T, &T)->Option<Ordering>, T > OrderOperatorByFn< F, T > { 
    pub fn new( order_operator_unwrapped: F ) 
            -> 
            OrderOperatorByFn< F, T > 
    { OrderOperatorByFn{ order_operator_unwrapped, phantom_comparatee: PhantomData } } 
}

// Copy
impl <T, F: Fn(&T, &T)->Option<Ordering> > 

    Clone for 
    
    OrderOperatorByFn
        < F, T > 

    where 
        F:  Clone,
{
    fn clone(&self) -> Self { OrderOperatorByFn::new( self.order_operator_unwrapped.clone() ) }
} 

// Copy
impl <T, F: Fn(&T, &T)->Option<Ordering> > 

    Copy for 
    
    OrderOperatorByFn
        < F, T > 

    where 
        F:  Clone + Copy,      
{ }  


// partial order
impl <T, F: Fn(&T, &T)->Option<Ordering> > 

    JudgePartialOrder
        <T> for 
    OrderOperatorByFn
        < F, T > 
{
    // fn lt( & self, a: &T, b: &T) -> bool {
    //     (self.order_operator_unwrapped)(a, b)
    // }
    fn judge_partial_cmp
            ( & self, left: & T, right: & T ) 
            -> 
            Option<Ordering> {
        (self.order_operator_unwrapped)( left, right )
    }
}



//  Mutable closure -- generatoed from a "less than" comparison
//  ---------------------------------------------

/// Determines order based on a user-supplied funcion that returns `bool`
/// 
/// Concretely, this is a wrapper for objects that implement `FnMut(&T, &T)->bool`.
/// If `x` is such an object, then we say `a < b` if `x( &a, &b ) = true`.
/// 
/// # See also
/// 
/// See See the documentation for the [order](crate::utilities::order) module for an overview on order operators.
#[derive(Debug, Eq, PartialEq)]
pub struct OrderOperatorByLessThan
                < F: Fn(&T, &T)->bool, T > 
{ 
    order_operator_unwrapped:         F, 
    phantom_comparatee:                 PhantomData< T > 
}

impl < F: Fn(&T, &T)->bool, T > OrderOperatorByLessThan< F, T > { 
    pub fn new( order_operator_unwrapped: F ) 
            -> 
            OrderOperatorByLessThan< F, T > 
    { OrderOperatorByLessThan{ order_operator_unwrapped, phantom_comparatee: PhantomData } } 
}


// Clone
impl <T, F: Fn(&T, &T)->bool > 

    Clone for 
    
    OrderOperatorByLessThan
        < F, T > 

    where 
        F:  Clone,
{
    fn clone(&self) -> Self { OrderOperatorByLessThan::new( self.order_operator_unwrapped.clone() ) }
} 

// Copy
impl <T, F: Fn(&T, &T)->bool > 

    Copy for 
    
    OrderOperatorByLessThan
        < F, T > 

    where 
        F:  Clone + Copy,      
{ }  


// Judge partial order
impl <T, F: Fn(&T, &T)->bool > 

    JudgePartialOrder
        <T> for 

    OrderOperatorByLessThan
        < F, T > 
{
    fn judge_partial_cmp
            ( & self, left: & T, right: & T ) 
            -> 
            Option<Ordering> {
        if (self.order_operator_unwrapped)( left, right ) { return Some(Ordering::Less) }
        if (self.order_operator_unwrapped)( right, left ) { return Some(Ordering::Greater) }
        Some(Ordering::Equal)
    }

    fn judge_lt( &self, left: & T, right: & T ) -> bool { (self.order_operator_unwrapped)( left, right ) }
}

impl <T, F: Fn(&T, &T)->bool > 

    JudgeOrder
        <T> for 

    OrderOperatorByLessThan
        < F, T > 
{
    fn judge_cmp
            ( & self, left: & T, right: & T ) 
            -> 
            Ordering {
        if (self.order_operator_unwrapped)( left, right ) { return Ordering::Less }
        if (self.order_operator_unwrapped)( right, left ) { return Ordering::Greater }
        Ordering::Equal
    }
}







//  Order first by LENGTH, then LEXICOGRAPHIC
//  -------------------------------------------------------------------------------------------------


/// Orders vectors first by length, then by lexicographic order
/// 
/// # Example
/// 
/// ```
/// use oat_rust::utilities::order::{ JudgePartialOrder, JudgeOrder, LexicographicOrderDominatedBylength};
/// use std::cmp::Ordering;
/// 
/// // create an instance of the order operator
/// let order_operator = LexicographicOrderDominatedBylength::new();
/// 
/// // partial order comparisons
/// // ---------------------------------
/// 
/// assert!( 
///     Some( Ordering::Less ) ==
///     order_operator.judge_partial_cmp( 
///         &vec![0],
///         &vec![1]
///     ) 
/// );
/// 
/// assert!( 
///     Some( Ordering::Greater ) ==
///     order_operator.judge_partial_cmp( 
///         &vec![0,1],
///         &vec![1]
///     )
/// );
/// 
/// assert!( 
///     Some( Ordering::Less ) ==
///     order_operator.judge_partial_cmp( 
///         &vec![0],
///         &vec![1,2]
///     )
/// );
/// 
/// assert!( 
///     Some( Ordering::Equal ) ==
///     order_operator.judge_partial_cmp( 
///         &vec![0],
///         &vec![0]
///     )
/// );
/// 
/// // order comparisons
/// // ---------------------------------
/// 
/// assert!( 
///     Ordering::Less ==
///     order_operator.judge_cmp( 
///         &vec![0],
///         &vec![1]
///     )
/// );
/// 
/// assert!( 
///     Ordering::Greater ==
///     order_operator.judge_cmp( 
///         &vec![0,1],
///         &vec![1]
///     )
/// );
/// 
/// assert!( 
///     Ordering::Less ==
///     order_operator.judge_cmp( 
///         &vec![0],
///         &vec![1,2]
///     )
/// );
/// 
/// assert!( 
///     Ordering::Equal ==
///     order_operator.judge_cmp( 
///         &vec![0],
///         &vec![0]
///     )
/// );    
/// ```
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Copy, new)]
pub struct LexicographicOrderDominatedBylength{}

impl < T >

    JudgePartialOrder< Vec<T> > for 
    
    LexicographicOrderDominatedBylength

    where
        T:  PartialOrd
{
    fn judge_partial_cmp
        ( & self, left: & Vec<T>, right: & Vec<T> ) 
        -> 
        Option<Ordering>
    {
        let left_len = left.len();
        let right_len = right.len();
        match left_len.cmp( & right_len ) {
            Ordering::Equal => { left.partial_cmp(right)  },
            Ordering::Less => { Some( Ordering::Less ) },
            Ordering::Greater => { Some( Ordering::Greater ) }
        }
    }             
}    


impl < T >

    JudgeOrder< Vec<T> > for 
    
    LexicographicOrderDominatedBylength

    where
        T:  Ord
{
    fn judge_cmp
        ( & self, left: & Vec<T>, right: & Vec<T> ) 
        -> 
        Ordering
    {
        let left_len = left.len();
        let right_len = right.len();
        match left_len.cmp( & right_len ) {
            Ordering::Equal => { left.cmp(right)  },
            Ordering::Less => { Ordering::Less },
            Ordering::Greater => { Ordering::Greater }
        }
    }      
}   
















//  Order first by REVERSE LENGTH, then LEXICOGRAPHIC
//  -------------------------------------------------------------------------------------------------


/// Orders vectors first by length, then by lexicographic order
/// 
/// # Example
/// 
/// ```
/// use oat_rust::utilities::order::{ JudgePartialOrder, JudgeOrder, LexicographicOrderDominatedByReverselength};
/// use std::cmp::Ordering;
/// 
/// // create an instance of the order operator
/// let order_operator = LexicographicOrderDominatedByReverselength::new();
/// 
/// // partial order comparisons
/// // ---------------------------------
/// 
/// assert!( 
///     Some( Ordering::Less ) ==
///     order_operator.judge_partial_cmp( 
///         &vec![0],
///         &vec![1]
///     ) 
/// );
/// 
/// assert!( 
///     Some( Ordering::Less ) ==
///     order_operator.judge_partial_cmp( 
///         &vec![0,1],
///         &vec![1]
///     )
/// );
/// 
/// assert!( 
///     Some( Ordering::Greater ) ==
///     order_operator.judge_partial_cmp( 
///         &vec![0],
///         &vec![1,2]
///     )
/// );
/// 
/// assert!( 
///     Some( Ordering::Equal ) ==
///     order_operator.judge_partial_cmp( 
///         &vec![0],
///         &vec![0]
///     )
/// );
/// 
/// // order comparisons
/// // ---------------------------------
/// 
/// assert!( 
///     Ordering::Less ==
///     order_operator.judge_cmp( 
///         &vec![0],
///         &vec![1]
///     )
/// );
/// 
/// assert!( 
///     Ordering::Less ==
///     order_operator.judge_cmp( 
///         &vec![0,1],
///         &vec![1]
///     )
/// );
/// 
/// assert!( 
///     Ordering::Greater ==
///     order_operator.judge_cmp( 
///         &vec![0],
///         &vec![1,2]
///     )
/// );
/// 
/// assert!( 
///     Ordering::Equal ==
///     order_operator.judge_cmp( 
///         &vec![0],
///         &vec![0]
///     )
/// );    
/// ```
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Copy, new)]
pub struct LexicographicOrderDominatedByReverselength{}

impl < T >

    JudgePartialOrder< Vec<T> > for 
    
    LexicographicOrderDominatedByReverselength

    where
        T:  PartialOrd
{
    fn judge_partial_cmp
        ( & self, left: & Vec<T>, right: & Vec<T> ) 
        -> 
        Option<Ordering>
    {
        let left_len = left.len();
        let right_len = right.len();
        match left_len.cmp( & right_len ) {
            Ordering::Equal => { left.partial_cmp(right)  },
            Ordering::Less => { Some( Ordering::Greater ) },
            Ordering::Greater => { Some( Ordering::Less ) }
        }
    }             
}    


impl < T >

    JudgeOrder< Vec<T> > for 
    
    LexicographicOrderDominatedByReverselength

    where
        T:  Ord
{
    fn judge_cmp
        ( & self, left: & Vec<T>, right: & Vec<T> ) 
        -> 
        Ordering
    {
        let left_len = left.len();
        let right_len = right.len();
        match left_len.cmp( & right_len ) {
            Ordering::Equal => { left.cmp(right)  },
            Ordering::Less => { Ordering::Greater },
            Ordering::Greater => { Ordering::Less }
        }
    }      
}   



























//  TESTS
//  ========================================================



#[cfg(test)]
mod tests {

    // Note this useful idiom: importing names from outer (for mod tests) scope.
    use super::*;


    #[test]
    fn define_order_operator() {     
        use crate::utilities::order::JudgePartialOrder;

        //  Define a new type of struct
        //  ---------------------------        
        pub struct MyOrderOperator;

        //  Implement the JudgePartialOrder trait on our new struct
        //  -------------------------------------------------------
        impl JudgePartialOrder< usize > for MyOrderOperator {

            // this function should return true iff left >= right
            fn judge_ge(&self,left: &usize, right: &usize) -> bool {
                left >= right 
            }
            // this function should return true iff left > right
            fn judge_gt(&self,left: &usize, right: &usize) -> bool {
                left > right
            }
            // this function should return true iff left <= right
            fn judge_le(&self,left: &usize, right: &usize) -> bool {
                left <= right
            }
            // this function should return true iff left < right
            fn judge_lt(&self, left: &usize, right: &usize ) -> bool {
                left < right
            }
            fn judge_partial_cmp( & self, left: & usize, right: & usize )  -> Option<Ordering> {
                Some( left.cmp( right ) )
            }
        }

        //  Implement the JudgeOrder trait on our new struct
        //  ------------------------------------------------
        impl JudgeOrder< usize > for MyOrderOperator {
            // the judge_clamp function in OAT is modeled off of the clamp function here: https://doc.rust-lang.org/std/cmp/trait.Ord.html
            fn judge_clamp(&self, clampee: usize, min: usize, max: usize) -> usize {
                clampee.clamp(min,max) // here we just use Rust's built-in clamp function
            }
            // the judge_cmp function in OAT is modeled off of the clamp function here: https://doc.rust-lang.org/std/cmp/trait.Ord.html            
            fn judge_cmp(&self, left: &usize, right: &usize ) -> Ordering {
                left.cmp(right)
            }
            // should return the maximum of left and right
            fn judge_max(&self, left: usize, right: usize) -> usize {
                left.max(right)
            }
            // should return the minimum of left and right
            fn judge_min(&self, left: usize, right: usize) -> usize {
                left.min(right)
            }
        }

        //  Use the trait
        fn compare_order() {
            let a = 1usize;
            let b = 2usize;
            let order_operator = MyOrderOperator;

            if order_operator.judge_lt( &a, &b ) { println!("a is strictly less than b") }
            else { println!("a is greater than or equal to b")}
        }

    }

}