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
//! # Categorical Utilities
//!
//! This module provides utility functions inspired by category theory concepts,
//! specifically designed to work with Rust's type safety and ownership system.
//! These utilities extend common operations on `Option`, `Result`, and other
//! functorial types while maintaining purity and immutability.
//!
//! ## Design Philosophy
//!
//! The utilities follow the principle: **Categorical Correctness > Type Safety > Performance**
//!
//! - **Categorical Correctness**: All functions preserve the mathematical laws of
//! functors, applicatives, and monads
//! - **Type Safety**: Leverages Rust's generics and ownership to ensure memory safety
//!
//! ## Core Concepts
//!
//! ### Functor-Inspired Mapping
//! Functions that preserve structure while transforming contents, following the
//! functor laws of identity and composition.
//!
//! ### Monad-Inspired Chaining
//! Functions that enable sequencing of computations with context, following the
//! monad laws of left identity, right identity, and associativity.
//!
//! ### Immutability and Purity
//! All functions avoid mutable state and side effects, promoting functional
//! programming patterns that are safe and predictable.
//!
//! ## Quick Start
//!
//! ```rust
//! use rustica::utils::categorical_utils::*;
//!
//! // Functor-inspired mapping
//! let maybe_num = Some(42);
//! let maybe_string = map_option(maybe_num, |x| x.to_string());
//! assert_eq!(maybe_string, Some("42".to_string()));
//!
//! // Monad-inspired chaining
//! let result = flat_map_result(Ok(10), |x| {
//! if x > 0 { Ok(x * 2) } else { Err("negative") }
//! });
//! assert_eq!(result, Ok(20));
//!
//! // Function composition: compose(g, f) means "g after f"
//! let add_one = |x: i32| x + 1;
//! let double = |x: i32| x * 2;
//! let composed = compose(double, add_one);
//! assert_eq!(composed(5), 12); // double(add_one(5)) = (5 + 1) * 2
//!
//! // Argument flipping: flip(f)(a, b) = f(b, a)
//! let subtract = |x: i32, y: i32| x - y;
//! let flipped_subtract = flip(subtract);
//! assert_eq!(flipped_subtract(3, 10), 7); // subtract(10, 3) = 10 - 3 = 7
//! ```
use crateMonoid;
// ===== Functor-Inspired Mapping Helpers =====
/// Maps a function over an `Option` value, preserving the structure.
///
/// This function applies the functor pattern to `Option` types, following the
/// mathematical laws of functors:
/// - Identity: `map_option(opt, |x| x) == opt`
/// - Composition: `map_option(map_option(opt, f), g) == map_option(opt, |x| g(f(x)))`
///
/// # Arguments
///
/// * `opt` - The `Option` value to map over
/// * `f` - The function to apply to the contained value (if `Some`)
///
/// # Returns
///
/// A new `Option` with the function applied to the contained value
///
/// # Examples
///
/// ```rust
/// use rustica::utils::categorical_utils::map_option;
///
/// // Transform a Some value
/// let result = map_option(Some(42), |x| x * 2);
/// assert_eq!(result, Some(84));
///
/// // None values remain None
/// let result: Option<i32> = map_option(None, |x: i32| x * 2);
/// assert_eq!(result, None);
///
/// // Chaining transformations
/// let result = map_option(
/// map_option(Some("hello"), |s| s.to_uppercase()),
/// |s| format!("{}!", s)
/// );
/// assert_eq!(result, Some("HELLO!".to_string()));
/// ```
///
/// # Type Class Laws
///
/// This function satisfies the functor laws:
///
/// ```rust
/// use rustica::utils::categorical_utils::map_option;
///
/// // Identity Law: mapping with identity function returns the original
/// let original = Some(42);
/// assert_eq!(map_option(original, |x| x), original);
///
/// // Composition Law: mapping f then g equals mapping the composition
/// let f = |x: i32| x + 1;
/// let g = |x: i32| x * 2;
/// let option = Some(5);
///
/// let result1 = map_option(map_option(option, f), g);
/// let result2 = map_option(option, |x| g(f(x)));
/// assert_eq!(result1, result2);
/// ```
/// Maps a function over the success value of a `Result`, preserving error cases.
///
/// This function applies the functor pattern to `Result` types, transforming
/// the success value while leaving error cases unchanged.
///
/// # Arguments
///
/// * `result` - The `Result` value to map over
/// * `f` - The function to apply to the success value (if `Ok`)
///
/// # Returns
///
/// A new `Result` with the function applied to the success value
///
/// # Examples
///
/// ```rust
/// use rustica::utils::categorical_utils::map_result;
///
/// // Transform a success value
/// let result: Result<String, &str> = map_result(Ok(42), |x| x.to_string());
/// assert_eq!(result, Ok("42".to_string()));
///
/// // Error values remain unchanged
/// let result: Result<String, &str> = map_result(Err("error"), |x: i32| x.to_string());
/// assert_eq!(result, Err("error"));
/// ```
/// Maps a function over both the error and success values of a `Result`.
///
/// This function provides bimap functionality for `Result` types, allowing
/// transformation of both the success and error cases simultaneously.
///
/// # Arguments
///
/// * `result` - The `Result` value to map over
/// * `f_ok` - Function to apply to the success value
/// * `f_err` - Function to apply to the error value
///
/// # Returns
///
/// A new `Result` with both success and error cases potentially transformed
///
/// # Examples
///
/// ```rust
/// use rustica::utils::categorical_utils::bimap_result;
///
/// // Transform both success and error cases
/// let success: Result<i32, &str> = Ok(42);
/// let result = bimap_result(success, |x| x * 2, |e| e.to_uppercase());
/// assert_eq!(result, Ok(84));
///
/// let error: Result<i32, &str> = Err("error");
/// let result = bimap_result(error, |x| x * 2, |e| e.to_uppercase());
/// assert_eq!(result, Err("ERROR".to_string()));
/// ```
// ===== Monad-Inspired Chaining Helpers =====
/// Chains computations on `Option` values using monadic bind.
///
/// This function applies the monad pattern to `Option` types, enabling
/// sequencing of computations that may fail. It follows the monad laws:
/// - Left Identity: `flat_map_option(Some(x), f) == f(x)`
/// - Right Identity: `flat_map_option(opt, Some) == opt`
/// - Associativity: `flat_map_option(flat_map_option(opt, f), g) == flat_map_option(opt, |x| flat_map_option(f(x), g))`
///
/// # Arguments
///
/// * `opt` - The `Option` value to chain from
/// * `f` - The function that returns an `Option` (monadic operation)
///
/// # Returns
///
/// The result of the monadic computation
///
/// # Examples
///
/// ```rust
/// use rustica::utils::categorical_utils::flat_map_option;
///
/// // Chain successful computations
/// let safe_divide = |x: i32, y: i32| -> Option<i32> {
/// if y != 0 { Some(x / y) } else { None }
/// };
///
/// let result = flat_map_option(Some(20), |x| safe_divide(x, 4));
/// assert_eq!(result, Some(5));
///
/// // Chain operations that may fail
/// let result = flat_map_option(Some(10), |x| safe_divide(x, 0));
/// assert_eq!(result, None);
///
/// // None values short-circuit
/// let result = flat_map_option(None, |x: i32| Some(x * 2));
/// assert_eq!(result, None);
/// ```
/// Chains computations on `Result` values using monadic bind.
///
/// This function applies the monad pattern to `Result` types, enabling
/// sequencing of computations that may fail with error propagation.
///
/// # Arguments
///
/// * `result` - The `Result` value to chain from
/// * `f` - The function that returns a `Result` (monadic operation)
///
/// # Returns
///
/// The result of the monadic computation
///
/// # Examples
///
/// ```rust
/// use rustica::utils::categorical_utils::flat_map_result;
///
/// // Chain successful computations
/// let parse_and_double = |s: &str| -> Result<i32, &'static str> {
/// s.parse::<i32>().map(|x| x * 2).map_err(|_| "parse error")
/// };
///
/// let result = flat_map_result(Ok("21"), parse_and_double);
/// assert_eq!(result, Ok(42));
///
/// // Error propagation
/// let result = flat_map_result(Err("initial error"), parse_and_double);
/// assert_eq!(result, Err("initial error"));
/// ```
// ===== Function Composition Utilities =====
/// Composes two functions, creating a new function that applies `f` first, then `g`.
///
/// This function implements mathematical function composition: `(g ∘ f)(x) = g(f(x))`.
/// Note that the argument order follows mathematical convention where `compose(g, f)`
/// means "g after f", so `f` is applied first and `g` is applied to its result.
///
/// The composition follows the associativity law and provides a pure functional approach
/// to combining operations.
///
/// # Arguments
///
/// * `g` - The outer function, applied second to the result of `f`
/// * `f` - The inner function, applied first to the input
///
/// # Returns
///
/// A new function that represents the composition `g ∘ f`
///
/// # Examples
///
/// ```rust
/// use rustica::utils::categorical_utils::compose;
///
/// let add_one = |x: i32| x + 1;
/// let double = |x: i32| x * 2;
///
/// // Compose functions: compose(double, add_one) means "double after add_one"
/// // So add_one is applied first, then double
/// let add_one_then_double = compose(double, add_one);
/// assert_eq!(add_one_then_double(5), 12); // double(add_one(5)) = (5 + 1) * 2
///
/// // Function composition is associative
/// let triple = |x: i32| x * 3;
/// let comp1 = compose(triple, compose(double, add_one));
/// let comp2 = compose(compose(triple, double), add_one);
/// assert_eq!(comp1(2), comp2(2));
/// ```
/// Pipes the output of one function into another, creating a pipeline.
///
/// This function implements function piping: `pipe(f, g)(x) = g(f(x))`.
/// Unlike `compose`, which reads right-to-left, `pipe` reads left-to-right,
/// making it more intuitive for sequential data transformations.
///
/// # Arguments
///
/// * `f` - The first function to apply
/// * `g` - The second function to apply to the result of the first
///
/// # Returns
///
/// A new function that represents the pipeline of `f` then `g`
///
/// # Examples
///
/// ```rust
/// use rustica::utils::categorical_utils::pipe;
///
/// let add_one = |x: i32| x + 1;
/// let double = |x: i32| x * 2;
///
/// // Pipe functions: first add one, then double
/// let add_one_then_double = pipe(add_one, double);
/// assert_eq!(add_one_then_double(5), 12); // (5 + 1) * 2
///
/// // Chain multiple transformations
/// let to_string = |x: i32| x.to_string();
/// let pipeline = pipe(pipe(add_one, double), to_string);
/// assert_eq!(pipeline(3), "8"); // (3 + 1) * 2 = "8"
/// ```
/// Flips the arguments of a two-argument function.
///
/// This function takes a function `f(a, b) -> c` and returns a function `f(b, a) -> c`,
/// effectively swapping the order of arguments. This is useful for partial application
/// and function composition.
///
/// # Arguments
///
/// * `f` - The function whose arguments should be flipped
///
/// # Returns
///
/// A function with arguments in reverse order
///
/// # Examples
///
/// ```rust
/// use rustica::utils::categorical_utils::flip;
///
/// // Original function that subtracts second from first
/// let subtract = |x: i32, y: i32| x - y;
///
/// // Flip the arguments
/// let flipped_subtract = flip(subtract);
///
/// assert_eq!(subtract(10, 3), 7); // 10 - 3 = 7
/// assert_eq!(flipped_subtract(10, 3), -7); // flip swaps args: subtract(3, 10) = 3 - 10 = -7
///
/// // Useful for creating different partial applications
/// let divide = |x: f64, y: f64| x / y;
/// let flipped_divide = flip(divide);
///
/// // Now we can easily create "divide into X" functions
/// let numbers = vec![8.0, 4.0, 2.0];
/// let halved: Vec<f64> = numbers.iter().map(|x| flipped_divide(2.0, *x)).collect();
/// assert_eq!(halved, vec![4.0, 2.0, 1.0]);
/// ```
// ===== Collection Utilities =====
/// Filters and maps over a collection in a single pass, preserving only successful transformations.
///
/// This function combines filtering with mapping and Option handling, applying a function
/// that returns `Option<U>` and keeping only the `Some` results. This is equivalent to
/// the Haskell `mapMaybe` function.
///
/// # Arguments
///
/// * `iter` - An iterator over the input collection
/// * `f` - A function that transforms elements to `Option<U>`
///
/// # Returns
///
/// A vector containing only the successful transformations
///
/// # Examples
///
/// ```rust
/// use rustica::utils::categorical_utils::filter_map_collect;
///
/// let numbers = vec!["1", "not_a_number", "3", "4", "not_a_number"];
///
/// // Parse numbers, keeping only successful parses
/// let parsed = filter_map_collect(
/// numbers.iter(),
/// |s| s.parse::<i32>().ok()
/// );
///
/// assert_eq!(parsed, vec![1, 3, 4]);
///
/// // Transform and filter in one step
/// let doubled_evens = filter_map_collect(
/// (1..=10).into_iter(),
/// |x| if x % 2 == 0 { Some(x * 2) } else { None }
/// );
///
/// assert_eq!(doubled_evens, vec![4, 8, 12, 16, 20]);
/// ```
/// Sequences a vector of `Option` values into an `Option` of vector.
///
/// This function converts `Vec<Option<T>>` to `Option<Vec<T>>`, succeeding only
/// if all elements are `Some`. This is a common operation in functional programming
/// for handling collections of optional values.
///
/// # Arguments
///
/// * `options` - A vector of `Option` values
///
/// # Returns
///
/// `Some(Vec<T>)` if all elements are `Some`, otherwise `None`
///
/// # Examples
///
/// ```rust
/// use rustica::utils::categorical_utils::sequence_options;
///
/// // All Some values
/// let all_some = vec![Some(1), Some(2), Some(3)];
/// let result = sequence_options(all_some);
/// assert_eq!(result, Some(vec![1, 2, 3]));
///
/// // Contains None
/// let has_none = vec![Some(1), None, Some(3)];
/// let result = sequence_options(has_none);
/// assert_eq!(result, None);
///
/// // Empty vector
/// let empty: Vec<Option<i32>> = vec![];
/// let result = sequence_options(empty);
/// assert_eq!(result, Some(vec![]));
/// ```
/// Sequences a vector of `Result` values into a `Result` of vector.
///
/// This function converts `Vec<Result<T, E>>` to `Result<Vec<T>, E>`, succeeding only
/// if all elements are `Ok`. Returns the first error encountered if any exist.
///
/// # Arguments
///
/// * `results` - A vector of `Result` values
///
/// # Returns
///
/// `Ok(Vec<T>)` if all elements are `Ok`, otherwise the first `Err` encountered
///
/// # Examples
///
/// ```rust
/// use rustica::utils::categorical_utils::sequence_results;
///
/// // All Ok values
/// let all_ok: Vec<Result<i32, &str>> = vec![Ok(1), Ok(2), Ok(3)];
/// let result = sequence_results(all_ok);
/// assert_eq!(result, Ok(vec![1, 2, 3]));
///
/// // Contains Err
/// let has_err: Vec<Result<i32, &str>> = vec![Ok(1), Err("error"), Ok(3)];
/// let result = sequence_results(has_err);
/// assert_eq!(result, Err("error"));
/// ```
/// Folds an iterator using a monoid's combine operation with automatic wrapping.
///
/// This function converts each element to the monoid type `W` and combines them
/// using the monoid's `combine` operation. If the iterator is empty, returns the
/// monoid's identity element (`empty()`).
///
/// # Type Parameters
///
/// * `I` - Iterator type that yields items of type `T`
/// * `T` - Item type that can be converted to the monoid wrapper `W`
/// * `W` - Monoid wrapper type (Sum, Product, First, Last, Min, Max, etc.)
///
/// # Arguments
///
/// * `iter` - An iterator of items to fold
///
/// # Returns
///
/// The result of combining all elements, or the identity element if empty
///
/// # Examples
///
/// ```rust
/// use rustica::utils::categorical_utils::fold_with;
/// use rustica::datatypes::maybe::Maybe;
/// use rustica::datatypes::wrapper::{sum::Sum, product::Product, first::First, last::Last, min::Min, max::Max};
///
/// // Sum operations
/// let numbers = vec![1, 2, 3, 4, 5];
/// let total: Sum<i32> = fold_with(numbers);
/// assert_eq!(total.unwrap(), 15);
///
/// // Product operations
/// let factors = vec![2, 3, 4];
/// let product: Product<i32> = fold_with(factors);
/// assert_eq!(product.unwrap(), 24);
///
/// // First operations
/// let values = vec![10, 20, 30];
/// let first: First<i32> = fold_with(values.clone());
/// assert_eq!(first.unwrap(), 10);
///
/// // Last operations
/// let last: Last<i32> = fold_with(values);
/// assert_eq!(last.unwrap(), 30);
///
/// // Min operations
/// let unsorted = vec![5, 2, 8, 1, 9];
/// let minimum: Min<i32> = fold_with(unsorted);
/// assert_eq!(minimum.unwrap(), 1);
///
/// // Max operations
/// let values = vec![3, 7, 2, 9, 4];
/// let maximum: Max<i32> = fold_with(values);
/// assert_eq!(maximum.unwrap(), 9);
///
/// // Empty iterator returns identity
/// let empty: Vec<i32> = vec![];
/// let zero: Sum<i32> = fold_with(empty);
/// assert_eq!(zero.unwrap(), 0);
/// ```