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
//! This module provides the `First` wrapper type which forms a semigroup by taking the first non-None value.
//!
//! ## Functional Programming Context
//!
//! The `First` type is a wrapper around `Option<T>` that implements various type classes with specific semantics:
//!
//! - As a `Semigroup`, it combines values by keeping the first non-None value
//! - As a `Monoid`, it uses `None` as its identity element
//! - As a `Functor`, it maps functions over the inner value if present
//!
//! ## Type Class Laws
//!
//! ### Semigroup Laws
//!
//! `First<T>` satisfies the semigroup associativity law:
//!
//! - **Associativity**: `(a ⊕ b) ⊕ c = a ⊕ (b ⊕ c)`
//!   - For all values a, b, and c, combining a and b and then combining the result with c
//!     yields the same result as combining a with the combination of b and c.
//!
//! ### Monoid Laws
//!
//! `First<T>` satisfies the monoid identity laws:
//!
//! - **Left Identity**: `empty() ⊕ a = a`
//!   - Combining the identity element (`First(None)`) with any value gives the original value.
//!
//! - **Right Identity**: `a ⊕ empty() = a`
//!   - Combining any value with the identity element gives the original value.
//!
//! ### Functor Laws
//!
//! `First<T>` satisfies the functor laws:
//!
//! - **Identity**: `fmap(id) = id`
//!   - Mapping the identity function over a `First` value gives the same value.
//!
//! - **Composition**: `fmap(f . g) = fmap(f) . fmap(g)`
//!   - Mapping a composed function is the same as mapping each function in sequence.
//!
//! ## Type Class Implementations
//!
//! `First<T>` implements the following type classes:
//!
//! - `Semigroup`: For any `T` that implements `Clone`
//! - `Monoid`: For any `T` that implements `Clone`
//! - `Functor`: For mapping operations over the inner value
//!
//! ## Quick Start
//!
//! ```rust
//! use rustica::datatypes::wrapper::first::First;
//! use rustica::traits::{semigroup::Semigroup, monoid::Monoid};
//!
//! // Create First wrappers
//! let a = First(Some(42));
//! let b = First(Some(10));
//! let none = First(None);
//!
//! // First non-None value wins
//! assert_eq!(a.combine(&b), First(Some(42))); // First value wins
//! assert_eq!(none.combine(&b), First(Some(10))); // Second value when first is None
//! assert_eq!(a.combine(&none), First(Some(42))); // First value when second is None
//!
//! // Identity element
//! let empty = First::empty();
//! assert_eq!(empty.combine(&a), a);
//! assert_eq!(a.combine(&empty), a);
//! ```
use crate::traits::functor::Functor;
use crate::traits::hkt::HKT;
use crate::traits::monoid::Monoid;
use crate::traits::semigroup::Semigroup;
use std::fmt;

/// A wrapper type that forms a semigroup by taking the first non-None value.
///
/// The monoid instance uses `None` as the identity element.
///
/// # Examples
///
/// Basic usage with the `Semigroup` trait:
///
/// ```rust
/// use rustica::datatypes::wrapper::first::First;
/// use rustica::traits::semigroup::Semigroup;
/// use rustica::traits::monoid::Monoid;
///
/// let a = First(Some(5));
/// let b = First(Some(7));
/// let c = a.combine(&b);
/// assert_eq!(c, First(Some(5)));
///
/// // First is associative
/// let x = First(Some(1));
/// let y = First(None);
/// let z = First(Some(3));
/// assert_eq!(x.clone().combine(&y.clone()).combine(&z.clone()),
///            x.clone().combine(&y.clone().combine(&z.clone())));
///
/// // Identity element
/// let id = First::empty();  // First(None)
/// assert_eq!(id, First(None));
/// assert_eq!(First(Some(42)).combine(&id.clone()), First(Some(42)));
/// assert_eq!(id.combine(&First(Some(42))), First(Some(42)));
/// ```
///
/// Using with `Functor` to transform the inner value:
///
/// ```rust
/// use rustica::datatypes::wrapper::first::First;
/// use rustica::traits::functor::Functor;
///
/// let a = First(Some(5));
/// let b = a.fmap(|x| x * 2);
/// assert_eq!(b, First(Some(10)));
///
/// let c = First(None);
/// let d = c.fmap(|x: &i32| x * 2);
/// assert_eq!(d, First(None));
/// ```
///
/// # Semigroup Laws
///
/// First satisfies the semigroup associativity law:
///
/// ```rust
/// use rustica::datatypes::wrapper::first::First;
/// use rustica::traits::semigroup::Semigroup;
///
/// // Verify associativity: (a ⊕ b) ⊕ c = a ⊕ (b ⊕ c)
/// fn verify_associativity<T: Clone + PartialEq>(a: First<T>, b: First<T>, c: First<T>) -> bool {
///     let left = a.clone().combine(&b).combine(&c);
///     let right = a.combine(&b.combine(&c));
///     left == right
/// }
///
/// // Test with various combinations
/// assert!(verify_associativity(First(Some(1)), First(Some(2)), First(Some(3))));
/// assert!(verify_associativity(First(None), First(Some(2)), First(Some(3))));
/// assert!(verify_associativity(First(Some(1)), First(None), First(Some(3))));
/// assert!(verify_associativity(First(Some(1)), First(Some(2)), First(None)));
/// ```
///
/// # Monoid Laws
///
/// First satisfies the monoid identity laws:
///
/// ```rust
/// use rustica::datatypes::wrapper::first::First;
/// use rustica::traits::monoid::Monoid;
/// use rustica::traits::semigroup::Semigroup;
///
/// // Verify left identity: empty() ⊕ a = a
/// fn verify_left_identity<T: Clone + PartialEq>(a: First<T>) -> bool {
///     let empty = First::empty();
///     empty.combine(&a) == a
/// }
///
/// // Verify right identity: a ⊕ empty() = a
/// fn verify_right_identity<T: Clone + PartialEq>(a: First<T>) -> bool {
///     let empty = First::empty();
///     a.combine(&empty) == a
/// }
///
/// // Test with Some and None values
/// assert!(verify_left_identity(First(Some(42))));
/// assert!(verify_left_identity::<i32>(First::empty()));
/// assert!(verify_right_identity(First(Some(42))));
/// assert!(verify_right_identity::<i32>(First::empty()));
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct First<T>(pub Option<T>);

impl<T: Clone> First<T> {
    /// Unwraps the first value, panicking if None.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use rustica::datatypes::wrapper::first::First;
    /// let first = First(Some(42));
    /// assert_eq!(first.unwrap(), 42);
    ///
    /// let empty: First<i32> = First(None);
    /// // empty.unwrap() would panic
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the inner value is None.
    pub fn unwrap(&self) -> T {
        self.0.clone().unwrap()
    }

    /// Unwraps the first value or returns a default.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use rustica::datatypes::wrapper::first::First;
    /// let first = First(Some(42));
    /// let empty = First(None);
    ///
    /// assert_eq!(first.unwrap_or(0), 42);
    /// assert_eq!(empty.unwrap_or(0), 0);
    /// ```
    pub fn unwrap_or(&self, default: T) -> T {
        self.0.clone().unwrap_or(default)
    }
}

impl<T> AsRef<T> for First<T> {
    #[inline]
    fn as_ref(&self) -> &T {
        self.0
            .as_ref()
            .expect("called `as_ref()` on an empty `First`")
    }
}

impl<T: Clone> Semigroup for First<T> {
    /// Combines two `First` values by taking the first non-None value, consuming both values.
    ///
    /// This is the owned version of the semigroup operation that takes ownership of both `self` and `other`.
    /// It returns the first value if it contains `Some`, otherwise it returns the second value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::wrapper::first::First;
    /// use rustica::traits::semigroup::Semigroup;
    ///
    /// // When first value is Some
    /// let a = First(Some(5));
    /// let b = First(Some(10));
    /// let c = a.combine_owned(b);
    /// assert_eq!(c, First(Some(5)));
    ///
    /// // When first value is None
    /// let x = First(None);
    /// let y = First(Some(7));
    /// let z = x.combine_owned(y);
    /// assert_eq!(z, First(Some(7)));
    ///
    /// // When both values are None
    /// let p = First::<i32>(None);
    /// let q = First::<i32>(None);
    /// let r = p.combine_owned(q);
    /// assert_eq!(r, First(None));
    /// ```
    #[inline]
    fn combine_owned(self, other: Self) -> Self {
        match self.0 {
            Some(_) => self,
            None => other,
        }
    }

    /// Combines two `First` values by taking the first non-None value, preserving the originals.
    ///
    /// This method implements the semigroup operation for `First` by returning a new `First`
    /// containing the first non-None value from either `self` or `other`. If both contain `None`,
    /// the result will be `First(None)`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::wrapper::first::First;
    /// use rustica::traits::semigroup::Semigroup;
    ///
    /// // When first value is Some
    /// let a = First(Some(5));
    /// let b = First(Some(10));
    /// let c = a.combine(&b);
    /// assert_eq!(c, First(Some(5)));
    /// // Original values are preserved
    /// assert_eq!(a, First(Some(5)));
    /// assert_eq!(b, First(Some(10)));
    ///
    /// // When first value is None
    /// let x = First(None);
    /// let y = First(Some(7));
    /// let z = x.combine(&y);
    /// assert_eq!(z, First(Some(7)));
    ///
    /// // Demonstrating associativity
    /// let v1 = First(None);
    /// let v2 = First(Some(10));
    /// let v3 = First(Some(20));
    ///
    /// // (v1 ⊕ v2) ⊕ v3 = v1 ⊕ (v2 ⊕ v3)
    /// let left = v1.combine(&v2).combine(&v3);
    /// let right = v1.combine(&v2.combine(&v3));
    /// assert_eq!(left, right);
    /// ```
    #[inline]
    fn combine(&self, other: &Self) -> Self {
        match &self.0 {
            Some(_) => First(self.0.clone()),
            None => First(other.0.clone()),
        }
    }
}

impl<T: fmt::Display> fmt::Display for First<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            Some(value) => write!(f, "First(Some({value}))"),
            None => write!(f, "First(None)"),
        }
    }
}

impl<T: Clone> Monoid for First<T> {
    /// Returns the identity element for the `First` monoid, which is `First(None)`.
    ///
    /// This method provides the identity element required by the `Monoid` type class.
    /// For `First`, this is represented as `None`, such that combining any value with
    /// `First(None)` returns the original value.
    ///
    /// # Type Class Laws
    ///
    /// ## Left Identity
    ///
    /// ```rust
    /// use rustica::datatypes::wrapper::first::First;
    /// use rustica::traits::monoid::Monoid;
    /// use rustica::traits::semigroup::Semigroup;
    ///
    /// // For any First(x), empty() ⊕ First(x) = First(x)
    /// let empty = First::<i32>::empty();
    /// let value = First(Some(42));
    ///
    /// assert_eq!(empty.combine(&value), value);
    /// ```
    ///
    /// ## Right Identity
    ///
    /// ```rust
    /// use rustica::datatypes::wrapper::first::First;
    /// use rustica::traits::monoid::Monoid;
    /// use rustica::traits::semigroup::Semigroup;
    ///
    /// // For any First(x), First(x) ⊕ empty() = First(x)
    /// let value = First(Some(42));
    /// let empty = First::<i32>::empty();
    ///
    /// assert_eq!(value.combine(&empty), value);
    /// ```
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::wrapper::first::First;
    /// use rustica::traits::monoid::Monoid;
    ///
    /// // Create an identity element
    /// let empty = First::<String>::empty();
    /// assert_eq!(empty, First(None));
    /// ```
    #[inline]
    fn empty() -> Self {
        First(None)
    }
}

impl<T> HKT for First<T> {
    type Source = T;
    type Output<U> = First<U>;
}

impl<T: Clone> Functor for First<T> {
    /// Maps a function over the inner value of this `First` container, if it exists.
    ///
    /// This method applies the function `f` to the inner value if it's `Some`,
    /// otherwise it returns `First(None)`. This borrows the inner value during the mapping.
    ///
    /// # Performance
    ///
    /// - **Time Complexity**: O(1) plus the complexity of function `f`
    /// - **Memory Usage**: Creates a new `First` wrapper with the transformed value
    /// - **Borrowing**: Takes a reference to the inner value, avoiding unnecessary clones
    ///
    /// # Type Class Laws
    ///
    /// ## Identity Law
    ///
    /// ```rust
    /// use rustica::datatypes::wrapper::first::First;
    /// use rustica::traits::functor::Functor;
    ///
    /// // For any First(x), fmap(id) = id
    /// // where id is the identity function
    /// fn verify_identity_law<T: Clone + PartialEq>(x: First<T>) -> bool {
    ///     let mapped = x.clone().fmap(|a| a.clone());
    ///     mapped == x
    /// }
    ///
    /// // Test with Some value
    /// assert!(verify_identity_law(First(Some(42))));
    ///
    /// // Test with None value
    /// assert!(verify_identity_law(First::<i32>(None)));
    /// ```
    ///
    /// ## Composition Law
    ///
    /// ```rust
    /// use rustica::datatypes::wrapper::first::First;
    /// use rustica::traits::functor::Functor;
    ///
    /// // For any First(x) and functions f and g:
    /// // fmap(f . g) = fmap(f) . fmap(g)
    /// fn verify_composition_law<T>(x: First<T>) -> bool
    /// where
    ///     T: Clone + PartialEq + std::fmt::Debug,
    ///     i32: From<T>,
    /// {
    ///     let f = |x: &i32| x * 2;
    ///     let g = |x: &T| i32::from(x.clone()) + 1;
    ///     
    ///     let left_side = x.clone().fmap(|a| f(&g(a)));
    ///     let right_side = x.clone().fmap(g).fmap(f);
    ///     
    ///     left_side == right_side
    /// }
    ///
    /// // Test with Some value (using i32 which implements From<i32>)
    /// assert!(verify_composition_law(First(Some(5))));
    ///
    /// // Test with None value
    /// assert!(verify_composition_law(First::<i32>(None)));
    /// ```
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::wrapper::first::First;
    /// use rustica::traits::functor::Functor;
    ///
    /// let a = First(Some(5));
    /// let b = a.fmap(|x| x * 2);
    /// assert_eq!(b, First(Some(10)));
    ///
    /// let c = First::<i32>(None);
    /// let d = c.fmap(|x| x * 2);
    /// assert_eq!(d, First(None));
    /// ```
    #[inline]
    fn fmap<U, F>(&self, f: F) -> Self::Output<U>
    where
        F: FnOnce(&Self::Source) -> U,
    {
        match &self.0 {
            Some(value) => First(Some(f(value))),
            None => First(None),
        }
    }

    /// Maps a function over the inner value of this `First` container, consuming it.
    ///
    /// This method is similar to `fmap` but takes ownership of `self` and passes ownership
    /// of the inner value to the function `f`. This is more efficient when you don't need
    /// to preserve the original container.
    ///
    /// # Performance
    ///
    /// - **Time Complexity**: O(1) plus the complexity of function `f`
    /// - **Memory Usage**: Creates a new `First` wrapper with the transformed value
    /// - **Ownership**: Consumes `self` and avoids unnecessary cloning of the inner value
    ///
    /// # Type Class Laws
    ///
    /// The same functor laws apply as for `fmap`, but with ownership semantics.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::wrapper::first::First;
    /// use rustica::traits::functor::Functor;
    ///
    /// let a = First(Some(String::from("hello")));
    /// let b = a.fmap_owned(|s| s.len());  // Consumes the string efficiently
    /// assert_eq!(b, First(Some(5)));
    ///
    /// // a is consumed and can't be used anymore
    /// ```
    #[inline]
    fn fmap_owned<U, F>(self, f: F) -> Self::Output<U>
    where
        F: FnOnce(Self::Source) -> U,
    {
        match self.0 {
            Some(value) => First(Some(f(value))),
            None => First(None),
        }
    }
}

impl<T> From<T> for First<T> {
    #[inline]
    fn from(value: T) -> Self {
        First(Some(value))
    }
}