rustica 0.12.0

Rustica is a functional programming library for the Rust language.
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
//! # Functor
//!
//! The `Functor` module provides trait definitions for implementing functors
//! in Rust, a fundamental abstraction in functional programming.
//!
//! A functor is a type constructor that supports a mapping operation which preserves
//! the structure of the functor while transforming its contents.
//!
//! ## Breaking Change (v0.11.0)
//!
//! The `Functor` trait no longer extends `Identity`. This aligns with category theory
//! where functors don't require value extraction capabilities. The `Identity` trait
//! is deprecated - use standard methods (`unwrap`, `as_ref`) or `Comonad::extract()` instead.
//!
//! ## Quick Start
//!
//! Transform values while preserving structure:
//!
//! ```rust
//! use rustica::traits::functor::Functor;
//! use rustica::datatypes::maybe::Maybe;
//!
//! // Transform values in context
//! let numbers = vec![1, 2, 3, 4, 5];
//! let doubled: Vec<i32> = numbers.fmap(|x| x * 2);
//! assert_eq!(doubled, vec![2, 4, 6, 8, 10]);
//!
//! // Works with optional values
//! let maybe_num = Maybe::Just(42);
//! let maybe_string = maybe_num.fmap(|x| x.to_string());
//! assert_eq!(maybe_string, Maybe::Just("42".to_string()));
//!
//! // Preserves structure - Nothing stays Nothing
//! let nothing: Maybe<i32> = Maybe::Nothing;
//! let still_nothing = nothing.fmap(|x| x.to_string());
//! assert_eq!(still_nothing, Maybe::Nothing);
//! ```
//!
//! ## Relationship to other traits
//!
//! Functors are the foundation of many higher-level abstractions in functional programming:
//!
//! ``` Text
//! Functor -> Applicative -> Monad
//! ```
//!
//! Each level adds more capabilities:
//! - Functors: Transforming values in a context (`fmap`)
//! - Applicatives: Applying functions in a context to values in a context (`apply`)
//! - Monads: Sequencing operations that return values in a context (`bind`)
//!
//! ## Components
//!
//! The module contains:
//!
//! - The core `Functor` trait that defines mapping operations
//! - Extension methods in `FunctorExt` for additional utility
//! - Implementations for standard Rust types like `Option`, `Result`, and `Vec`
//!
//! ## Functor Laws
//!
//! A proper functor should satisfy the following laws:
//!
//! ```rust
//! use rustica::traits::functor::Functor;
//!
//! // 1. Identity
//! let x: Option<i32> = Some(42);
//! assert_eq!(x.fmap(|v| v.clone()), x);
//!
//! // 2. Composition
//! let f = |x: &i32| x + 1;
//! let g = |x: &i32| x * 2;
//! let x: Option<i32> = Some(1);
//!
//! let result1: Option<i32> = x.fmap(|v| g(&f(v)));
//! let result2: Option<i32> = x.fmap(f).fmap(g);
//! assert_eq!(result1, result2);
//! ```

use crate::prelude::*;

/// A trait for functors, which are type constructors that support mapping over values.
///
/// In category theory, a functor is a mapping between categories that preserves
/// structure. In Rust terms, it's a type constructor that provides a way to apply
/// a function to values while preserving their structure.
///
/// # Functor Laws
///
/// Any implementation of `Functor` should satisfy these laws:
///
/// 1. Identity: `functor.fmap(|x| x) == functor`
///    Mapping the identity function over a functor should return an equivalent functor.
///
/// 2. Composition: `functor.fmap(|x| g(f(x))) == functor.fmap(f).fmap(g)`
///    Mapping a composition of functions should be the same as mapping each function in sequence.
///
/// # Examples
///
/// ```rust
/// use rustica::traits::functor::Functor;
/// use rustica::datatypes::maybe::Maybe;
///
/// // Using the Functor implementation for Maybe
/// let maybe_int = Maybe::Just(42);
///
/// // Transform i32 to String
/// let maybe_string = maybe_int.fmap(|x: &i32| x.to_string());
/// assert_eq!(maybe_string, Maybe::Just("42".to_string()));
///
/// // Using replace to substitute values
/// let replaced = maybe_int.replace(&String::from("hello"));
/// assert_eq!(replaced.unwrap(), "hello");
///
/// // Using void to discard values
/// let voided = maybe_int.void();
/// assert!(matches!(voided, Maybe::Just(())));
///
/// // With empty values
/// let maybe_none = Maybe::<i32>::Nothing;
/// let mapped_none = maybe_none.fmap(|x: &i32| x.to_string());
/// assert!(mapped_none.is_nothing());
/// ```
pub trait Functor: HKT {
    /// Maps a function over the values in a functor without consuming it.
    ///
    /// This is a reference-based version of `fmap` that doesn't consume the functor.
    ///
    /// # Arguments
    ///
    /// * `f` - A function that transforms values of type `Self::Source` into type `B`
    ///
    /// # Returns
    ///
    /// A new functor containing the transformed values
    fn fmap<B, F>(&self, f: F) -> Self::Output<B>
    where
        F: Fn(&Self::Source) -> B,
        B: Clone;

    /// Maps a function over the values in a functor.
    ///
    /// This operation applies the given function to each value inside the
    /// functor, preserving the structure while transforming the contents.
    ///
    /// # Arguments
    ///
    /// * `f` - A function that transforms values of type `Self::Source` into type `B`
    ///
    /// # Returns
    ///
    /// A new functor containing the transformed value.
    fn fmap_owned<B, F>(self, f: F) -> Self::Output<B>
    where
        F: Fn(Self::Source) -> B,
        B: Clone,
        Self: Sized;

    /// Replaces all values in the functor with a constant value, without consuming it.
    ///
    /// # Arguments
    ///
    /// * `value` - A reference to the value to replace all elements with
    ///
    /// # Returns
    ///
    /// A new functor with all elements replaced by a clone of the given value
    ///
    /// # Default Implementation
    ///
    /// Uses `map` to replace all values.
    #[inline]
    fn replace<B>(&self, value: &B) -> Self::Output<B>
    where
        B: Clone,
    {
        self.fmap(|_| value.clone())
    }

    /// Replaces all values in the functor with a constant value.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to replace all elements with
    ///
    /// # Returns
    ///
    /// A new functor with all elements replaced by the given value
    ///
    /// # Default Implementation
    ///
    /// Uses `map_owned` to replace all values.
    #[inline]
    fn replace_owned<B>(&self, value: B) -> Self::Output<B>
    where
        B: Clone,
        Self: Sized,
    {
        self.fmap(|_| value.clone())
    }

    /// Void functor - discards the values and replaces them with unit, without consuming the functor.
    ///
    /// # Returns
    ///
    /// A new functor with all elements replaced by ()
    ///
    /// # Default Implementation
    ///
    /// Uses `map` to replace all values with unit.
    #[inline]
    fn void(&self) -> Self::Output<()> {
        self.fmap(|_| ())
    }

    /// Void functor - discards the values and replaces them with unit.
    ///
    /// # Returns
    ///
    /// A new functor with all elements replaced by ()
    ///
    /// # Default Implementation
    ///
    /// Uses `map_owned` to replace all values with unit.
    #[inline]
    fn void_owned(self) -> Self::Output<()>
    where
        Self: Sized,
    {
        self.fmap_owned(|_| ())
    }
}

/// Extension trait for functors providing additional utility methods.
///
/// This trait extends the basic `Functor` trait with additional operations that
/// are common in functional programming but not essential to the functor concept.
///
/// # Examples
///
/// ```rust
/// use rustica::traits::functor::{Functor, FunctorExt};
/// use rustica::traits::hkt::HKT;
///
/// // Using FunctorExt methods with Option
/// let some_value: Option<i32> = Some(42);
///
/// // Using inspect to perform side effects without changing the value
/// let logged: Option<i32> = some_value.inspect(|x| {
///     println!("Value: {}", x);
/// });
/// assert_eq!(logged, Some(42));
///
/// // Using inspect_err on Result (should do nothing for Ok variant)
/// let ok_value: Result<i32, &str> = Ok(42);
/// let result = ok_value.inspect_err(|e| panic!("Should not be called for Ok: {}", e));
/// assert_eq!(result, Ok(42));
///
/// // Using filter_map to transform and potentially filter out values
/// let filter_mapped: Option<String> = some_value.filter_map(|x| {
///     if *x > 40 {
///         Some(x.to_string())
///     } else {
///         None
///     }
/// });
/// assert_eq!(filter_mapped, Some("42".to_string()));
///
/// // Working with vectors
/// let numbers: Vec<i32> = vec![1, 2, 3, 4, 5];
/// let even_squared: Vec<i32> = numbers.filter_map(|x| {
///     if x % 2 == 0 {
///         Some(x * x)
///     } else {
///         None
///     }
/// });
/// assert_eq!(even_squared, vec![4, 16]);
/// ```
pub trait FunctorExt: Functor {
    /// Transforms values with a fallible function, handling errors by providing a default value.
    ///
    /// # Arguments
    ///
    /// * `f` - A function that may fail
    /// * `default` - A default value to use in case of failure
    ///
    /// # Returns
    ///
    /// A new functor with transformed values or defaults in case of errors
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::functor::{Functor, FunctorExt};
    /// use rustica::traits::hkt::HKT;
    ///
    /// let some_value: Option<i32> = Some(42);
    ///
    /// // Using try_map_or with a fallible function
    /// let result: Option<String> = some_value.try_map_or(
    ///     "default".to_string(),
    ///     |x| -> Result<String, &str> {
    ///         if *x > 0 {
    ///             Ok(x.to_string())
    ///         } else {
    ///             Err("negative number")
    ///         }
    ///     }
    /// );
    /// assert_eq!(result, Some("42".to_string()));
    ///
    /// // With a value that causes an error
    /// let negative: Option<i32> = Some(-10);
    /// let result_with_default: Option<String> = negative.try_map_or(
    ///     "default".to_string(),
    ///     |x| -> Result<String, &str> {
    ///         if *x > 0 {
    ///             Ok(x.to_string())
    ///         } else {
    ///             Err("negative number")
    ///         }
    ///     }
    /// );
    /// assert_eq!(result_with_default, Some("default".to_string()));
    /// ```
    #[inline]
    fn try_map_or<B, E, F>(&self, default: B, f: F) -> Self::Output<B>
    where
        F: Fn(&Self::Source) -> Result<B, E>,
        B: Clone,
    {
        self.fmap(|a| match f(a) {
            Ok(b) => b,
            Err(_) => default.clone(),
        })
    }

    /// Transforms values with a fallible function, handling errors with a provided function.
    ///
    /// # Arguments
    ///
    /// * `f` - A function that may fail
    /// * `default_fn` - A function that provides a default value from the error
    ///
    /// # Returns
    ///
    /// A new functor with transformed values or computed defaults in case of errors
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::functor::{Functor, FunctorExt};
    /// use rustica::traits::hkt::HKT;
    ///
    /// let some_value: Option<i32> = Some(42);
    ///
    /// // Using try_map_or_else with a fallible function and error handler
    /// let result: Option<String> = some_value.try_map_or_else(
    ///     |err: &String| format!("Error: {}", err),
    ///     |x| -> Result<String, String> {
    ///         if *x > 0 {
    ///             Ok(x.to_string())
    ///         } else {
    ///             Err("negative number".to_string())
    ///         }
    ///     }
    /// );
    /// assert_eq!(result, Some("42".to_string()));
    ///
    /// // With a value that causes an error
    /// let negative: Option<i32> = Some(-10);
    /// let result_with_error_handler: Option<String> = negative.try_map_or_else(
    ///     |err: &String| format!("Error: {}", err),
    ///     |x| -> Result<String, String> {
    ///         if *x > 0 {
    ///             Ok(x.to_string())
    ///         } else {
    ///             Err("negative number".to_string())
    ///         }
    ///     }
    /// );
    /// assert_eq!(result_with_error_handler, Some("Error: negative number".to_string()));
    /// ```
    #[inline]
    fn try_map_or_else<B, E, D, F>(&self, default_fn: D, f: F) -> Self::Output<B>
    where
        F: Fn(&Self::Source) -> Result<B, E>,
        B: Clone,
        D: Fn(&E) -> B,
    {
        self.fmap(|a| match f(a) {
            Ok(b) => b,
            Err(e) => default_fn(&e),
        })
    }

    /// Transforms values with a function that might return None, filtering out None results.
    ///
    /// This combines mapping and filtering into a single operation.
    ///
    /// # Arguments
    ///
    /// * `f` - A function that returns an Option
    ///
    /// # Returns
    ///
    /// A new functor containing only the values for which the function returned Some
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::functor::{Functor, FunctorExt};
    /// use rustica::traits::hkt::HKT;
    ///
    /// let some_value: Option<i32> = Some(42);
    ///
    /// // Keep only values that pass a predicate and transform them
    /// let filter_mapped: Option<String> = some_value.filter_map(|x| {
    ///     if *x > 40 {
    ///         Some(x.to_string())
    ///     } else {
    ///         None
    ///     }
    /// });
    /// assert_eq!(filter_mapped, Some("42".to_string()));
    ///
    /// // Value filtered out
    /// let filtered_out: Option<String> = some_value.filter_map(|x| {
    ///     if *x > 100 {
    ///         Some(x.to_string())
    ///     } else {
    ///         None
    ///     }
    /// });
    /// assert_eq!(filtered_out, None);
    /// ```
    fn filter_map<B, F>(&self, f: F) -> Self::Output<B>
    where
        F: Fn(&Self::Source) -> Option<B>;
}

impl<T> Functor for Vec<T> {
    #[inline]
    fn fmap<B, F>(&self, f: F) -> Self::Output<B>
    where
        F: Fn(&Self::Source) -> B,
    {
        self.iter().map(f).collect()
    }

    #[inline]
    fn fmap_owned<B, F>(self, f: F) -> Self::Output<B>
    where
        F: Fn(Self::Source) -> B,
        Self: Sized,
    {
        self.into_iter().map(f).collect()
    }
}

impl<T> FunctorExt for Vec<T> {
    #[inline]
    fn filter_map<B, F>(&self, f: F) -> Self::Output<B>
    where
        F: FnMut(&Self::Source) -> Option<B>,
    {
        self.iter().filter_map(f).collect()
    }

    #[inline]
    fn try_map_or<B, E, F>(&self, default: B, f: F) -> Self::Output<B>
    where
        F: Fn(&Self::Source) -> Result<B, E>,
        B: Clone,
    {
        self.iter()
            .map(|x| match f(x) {
                Ok(b) => b,
                Err(_) => default.clone(),
            })
            .collect()
    }

    #[inline]
    fn try_map_or_else<B, E, D, F>(&self, default_fn: D, f: F) -> Self::Output<B>
    where
        F: Fn(&Self::Source) -> Result<B, E>,
        D: Fn(&E) -> B,
    {
        self.iter()
            .map(|x| match f(x) {
                Ok(b) => b,
                Err(e) => default_fn(&e),
            })
            .collect()
    }
}

impl<T> FunctorExt for Option<T> {
    #[inline]
    fn filter_map<B, F>(&self, f: F) -> Self::Output<B>
    where
        F: FnOnce(&Self::Source) -> Option<B>,
    {
        self.as_ref().and_then(f)
    }

    #[inline]
    fn try_map_or<B, E, F>(&self, default: B, f: F) -> Self::Output<B>
    where
        F: FnOnce(&Self::Source) -> Result<B, E>,
        B: Clone,
    {
        match self {
            Some(value) => match f(value) {
                Ok(b) => Some(b),
                Err(_) => Some(default.clone()),
            },
            None => None,
        }
    }

    #[inline]
    fn try_map_or_else<B, E, D, F>(&self, default_fn: D, f: F) -> Self::Output<B>
    where
        F: FnOnce(&Self::Source) -> Result<B, E>,
        D: Fn(&E) -> B,
    {
        match self {
            Some(value) => match f(value) {
                Ok(b) => Some(b),
                Err(e) => Some(default_fn(&e)),
            },
            None => None,
        }
    }
}

impl<T, E: std::fmt::Debug> FunctorExt for Result<T, E>
where
    E: Clone + Default,
{
    #[inline]
    fn filter_map<B, F>(&self, f: F) -> Self::Output<B>
    where
        F: FnOnce(&Self::Source) -> Option<B>,
    {
        match self {
            Ok(value) => match f(value) {
                Some(b) => Ok(b),
                None => Err(E::default()),
            },
            Err(e) => Err(e.clone()),
        }
    }

    #[inline]
    fn try_map_or<B, E2, F>(&self, default: B, f: F) -> Self::Output<B>
    where
        F: FnOnce(&Self::Source) -> Result<B, E2>,
        B: Clone,
    {
        match self {
            Ok(value) => match f(value) {
                Ok(b) => Ok(b),
                Err(_) => Ok(default.clone()),
            },
            Err(e) => Err(e.clone()),
        }
    }

    #[inline]
    fn try_map_or_else<B, E2, D, F>(&self, default_fn: D, f: F) -> Self::Output<B>
    where
        F: FnOnce(&Self::Source) -> Result<B, E2>,
        D: Fn(&E2) -> B,
    {
        match self {
            Ok(value) => match f(value) {
                Ok(b) => Ok(b),
                Err(e) => Ok(default_fn(&e)),
            },
            Err(e) => Err(e.clone()),
        }
    }
}

impl<T> Functor for Option<T> {
    #[inline]
    fn fmap<B, F>(&self, f: F) -> Self::Output<B>
    where
        F: Fn(&Self::Source) -> B,
        B: Clone,
    {
        self.as_ref().map(f)
    }

    #[inline]
    fn fmap_owned<B, F>(self, f: F) -> Self::Output<B>
    where
        F: Fn(Self::Source) -> B,
        Self: Sized,
    {
        self.map(f)
    }
}

impl<A, E: std::fmt::Debug + Clone> Functor for Result<A, E> {
    #[inline]
    fn fmap<B, F>(&self, f: F) -> Self::Output<B>
    where
        F: Fn(&Self::Source) -> B,
        B: Clone,
    {
        match self {
            Ok(value) => Ok(f(value)),
            Err(e) => Err(e.clone()),
        }
    }

    #[inline]
    fn fmap_owned<B, F>(self, f: F) -> Self::Output<B>
    where
        F: Fn(Self::Source) -> B,
        Self: Sized,
    {
        match self {
            Ok(value) => Ok(f(value)),
            Err(e) => Err(e.clone()),
        }
    }
}