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
635
636
637
638
639
640
641
642
643
644
//! # Pure
//!
//! The `Pure` module provides the `Pure` trait, which represents the ability to lift values
//! into a higher-kinded context. This is one of the fundamental operations in
//! functional programming, often called `return` or `unit` in other languages.
//!
//! # Mathematical Definition
//!
//! In category theory, `pure` corresponds to the η (eta) natural transformation that
//! maps values into a context.
//!
//! Note: laws involving `bind` (Monad) or `apply` (Applicative) only apply once `Pure` is used
//! together with those additional structures.
//!
//! # Core Concepts
//!
//! In functional programming, the ability to lift a value into a context is essential
//! for building composable abstractions. The `Pure` trait serves as the foundation for:
//!
//! - **Applicative Functors**: `pure` is one of the core operations of Applicative
//! - **Monads**: `pure` is equivalent to the `return` operation in monads
//! - **Effect Systems**: Wrapping values in computational contexts
//!
//! # Examples
//!
//! ```rust
//! use rustica::traits::hkt::HKT;
//! use rustica::traits::pure::Pure;
//!
//! // Using pure with Option
//! let value: i32 = 42;
//! let option: Option<i32> = <Option<i32> as Pure>::pure(&value);
//! assert_eq!(option, Some(42));
//!
//! // Using pure with Result
//! let result: Result<i32, &str> = <Result<i32, &str> as Pure>::pure(&value);
//! assert_eq!(result, Ok(42));
//!
//! // Using pure with Vec
//! let vec: Vec<i32> = <Vec<i32> as Pure>::pure(&value);
//! assert_eq!(vec, vec![42]);
//! ```
//!
//! # Extension Traits
//!
//! The `PureExt` trait provides extension methods for working with values that can be
//! lifted into a context:
//!
//! ```rust
//! use rustica::traits::hkt::HKT;
//! use rustica::traits::pure::{Pure, PureExt};
//!
//! // Using the to_pure extension method
//! let value: i32 = 42;
//! let option: Option<i32> = value.to_pure::<Option<i32>>();
//! assert_eq!(option, Some(42));
//!
//! // Using pair_with to combine two values
//! let a: i32 = 42;
//! let b: &str = "hello";
//! let pair: Option<(i32, &str)> = a.pair_with::<Option<(i32, &str)>, &str>(&b);
//! assert_eq!(pair, Some((42, "hello")));
//!
//! // Using lift_other to lift a value into the same context
//! let a: i32 = 42;
//! let b: &str = "hello";
//! let lifted: Option<&str> = a.lift_other::<Option<&str>, &str>(&b);
//! assert_eq!(lifted, Some("hello"));
//! ```

use crate::traits::hkt::HKT;
use std::marker::PhantomData;

/// A trait for types that can lift values into a higher-kinded context.
///
/// The `Pure` trait provides the fundamental operation of "lifting" a regular value
/// into a context. This is a core concept in functional programming, often referred to
/// as `return` or `unit` in other languages and frameworks.
///
/// # Type Parameters
/// The trait inherits type parameters from `HKT`:
/// * `Source`: The type of values being transformed
/// * `Output<T>`: The result type after transformation
///
/// # Laws
/// For a valid Pure implementation, the following laws must hold:
///
/// Note: the laws below are stated in terms of `fmap` and `apply`, so they apply when the
/// implementing type also forms a lawful `Functor`/`Applicative`.
///
/// 1. Identity Preservation:
///    ```text
///    pure(x).fmap(id) == pure(x)
///    ```
///    Lifting a value and then mapping the identity function over it should yield the same result.
///
/// 2. Homomorphism:
///    ```text
///    pure(f(x)) == pure(f).apply(pure(x))
///    ```
///    Applying a function to a value and then lifting the result should be the same as
///    lifting both the function and the value and then applying them.
///
/// # Examples
///
/// Basic implementation for a custom type:
/// ```rust
/// use rustica::traits::hkt::HKT;
/// use rustica::traits::pure::Pure;
///
/// // A simple wrapper type
/// struct MyWrapper<T>(T);
///
/// impl<T> HKT for MyWrapper<T> {
///     type Source = T;
///     type Output<U> = MyWrapper<U>;
/// }
///
/// impl<T> Pure for MyWrapper<T> {
///     fn pure<U: Clone>(value: &U) -> Self::Output<U> {
///         MyWrapper(value.clone())
///     }
///
///     // We can provide a more efficient implementation for pure_owned
///     fn pure_owned<U: Clone>(value: U) -> Self::Output<U> {
///         MyWrapper(value)
///     }
/// }
///
/// // Using our Pure implementation
/// let wrapped: MyWrapper<i32> = MyWrapper::<()>::pure(&42);
/// ```
pub trait Pure: HKT {
    /// Lift a value into a context.
    ///
    /// This method creates a new instance of the higher-kinded type containing the provided value.
    /// It operates on a reference to the value, which is cloned into the context.
    ///
    /// # Type Parameters
    /// * `T`: The type of the value to lift
    ///
    /// # Parameters
    /// * `value`: A reference to the value to lift
    ///
    /// # Returns
    /// A new instance of the higher-kinded type containing the value
    ///
    /// # Examples
    /// ```rust
    /// use rustica::traits::hkt::HKT;
    /// use rustica::traits::pure::Pure;
    ///
    /// let x = 42;
    /// let option: Option<i32> = <Option<i32> as Pure>::pure(&x);
    /// assert_eq!(option, Some(42));
    /// ```
    fn pure<T: Clone>(value: &T) -> Self::Output<T>;

    /// Lift a value into a context, consuming the value.
    ///
    /// This method is an ownership-based variant of `pure` that consumes the provided value
    /// instead of cloning it. This can be more efficient when the original value is no longer needed.
    ///
    /// # Type Parameters
    /// * `T`: The type of the value to lift
    ///
    /// # Parameters
    /// * `value`: The value to lift, which will be consumed
    ///
    /// # Returns
    /// A new instance of the higher-kinded type containing the value
    ///
    /// # Examples
    /// ```rust
    /// use rustica::traits::hkt::HKT;
    /// use rustica::traits::pure::Pure;
    ///
    /// let option: Option<i32> = <Option<i32> as Pure>::pure_owned(42);
    /// assert_eq!(option, Some(42));
    /// ```
    #[inline]
    fn pure_owned<T: Clone>(value: T) -> Self::Output<T> {
        Self::pure(&value)
    }
}

// Standard Library Implementations

impl<T> Pure for Option<T> {
    #[inline]
    fn pure<U: Clone>(value: &U) -> Self::Output<U> {
        Some(value.clone())
    }

    #[inline]
    fn pure_owned<U>(value: U) -> Self::Output<U> {
        Some(value)
    }
}

impl<T, E: Clone> Pure for Result<T, E> {
    #[inline]
    fn pure<U: Clone>(value: &U) -> Self::Output<U> {
        Ok(value.clone())
    }

    #[inline]
    fn pure_owned<U>(value: U) -> Self::Output<U> {
        Ok(value)
    }
}

impl<T> Pure for Vec<T> {
    #[inline]
    fn pure_owned<U>(value: U) -> Self::Output<U> {
        vec![value]
    }

    #[inline]
    fn pure<U: Clone>(value: &U) -> Self::Output<U> {
        vec![value.clone()]
    }
}

impl<T> Pure for Box<T> {
    #[inline]
    fn pure_owned<U>(value: U) -> Self::Output<U> {
        Box::new(value)
    }

    #[inline]
    fn pure<U: Clone>(value: &U) -> Self::Output<U> {
        Box::new(value.clone())
    }
}

/// Extension trait providing a more ergonomic way to use Pure.
///
/// This trait allows calling methods like `to_pure` directly on values, making it more
/// convenient to lift values into higher-kinded contexts and work with them.
///
/// # Implemented For
///
/// This trait is implemented for all types that implement `Clone`, which means
/// it can be used with any cloneable value.
///
/// # Examples
///
/// Using `to_pure` to lift a value into Option:
/// ```rust
/// use rustica::traits::hkt::HKT;
/// use rustica::traits::pure::{Pure, PureExt};
///
/// // Instead of: <Option<i32> as Pure>::pure(&42)
/// // We can write:
/// let value: i32 = 42;
/// let option: Option<i32> = value.to_pure::<Option<i32>>();
/// assert_eq!(option, Some(42));
/// ```
///
/// Chaining operations with the Validated type:
/// ```rust
/// use rustica::traits::hkt::HKT;
/// use rustica::traits::pure::{Pure, PureExt};
/// use rustica::traits::functor::Functor;
/// use rustica::datatypes::validated::Validated;
///
/// let value: i32 = 42;
///
/// // Lift into Validated context and transform
/// let validated: Validated<&str, i32> = value.to_pure::<Validated<&str, i32>>();
/// let doubled: Validated<&str, i32> = validated.fmap(|x: &i32| *x * 2);
///
/// assert!(matches!(doubled, Validated::Valid(84)));
/// ```
pub trait PureExt: Sized {
    /// Lift a value into a context.
    ///
    /// This method provides a more ergonomic way to use `Pure::pure`, allowing
    /// you to call it directly on values.
    ///
    /// # Type Parameters
    ///
    /// * `P`: The higher-kinded type to lift into, implementing `Pure`
    ///
    /// # Returns
    ///
    /// The value wrapped in the higher-kinded context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::hkt::HKT;
    /// use rustica::traits::pure::{Pure, PureExt};
    /// use rustica::datatypes::validated::Validated;
    ///
    /// let x: i32 = 42;
    ///
    /// // Lift into Option
    /// let option: Option<i32> = x.to_pure::<Option<i32>>();
    /// assert_eq!(option, Some(42));
    ///
    /// // Lift into Validated
    /// let validated: Validated<&str, i32> = x.to_pure::<Validated<&str, i32>>();
    /// assert!(matches!(validated, Validated::Valid(42)));
    /// ```
    #[inline]
    fn to_pure<P>(&self) -> P::Output<Self>
    where
        P: Pure,
        Self: Clone,
    {
        P::pure(self)
    }

    /// Lift a value into a context, consuming the value.
    ///
    /// This method provides a more efficient version of `to_pure` that consumes
    /// the value instead of cloning it.
    ///
    /// # Type Parameters
    ///
    /// * `P`: The higher-kinded type to lift into, implementing `Pure`
    ///
    /// # Returns
    ///
    /// The value wrapped in the higher-kinded context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::hkt::HKT;
    /// use rustica::traits::pure::{Pure, PureExt};
    ///
    /// // Using to_pure_owned (consumes the value)
    /// let option: Option<i32> = 42.to_pure_owned::<Option<i32>>();
    /// assert_eq!(option, Some(42));
    /// ```
    #[inline]
    fn to_pure_owned<P>(self) -> P::Output<Self>
    where
        P: Pure,
        Self: Clone,
    {
        P::pure_owned(self)
    }

    /// Lift a pair of values into a context.
    ///
    /// This method combines two values into a tuple and lifts the result
    /// into a higher-kinded context.
    ///
    /// # Type Parameters
    ///
    /// * `P`: The higher-kinded type to lift into, implementing `Pure`
    /// * `U`: The type of the second value
    ///
    /// # Parameters
    ///
    /// * `other`: A reference to the second value to pair with this one
    ///
    /// # Returns
    ///
    /// A pair of values in the higher-kinded context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::hkt::HKT;
    /// use rustica::traits::pure::{Pure, PureExt};
    /// use rustica::datatypes::validated::Validated;
    ///
    /// let a: i32 = 42;
    /// let b: &str = "hello";
    ///
    /// // Create a pair in Option context
    /// let option_pair: Option<(i32, &str)> = a.pair_with::<Option<(i32, &str)>, &str>(&b);
    /// assert_eq!(option_pair, Some((42, "hello")));
    ///
    /// // Create a pair in Validated context
    /// let validated_pair: Validated<&str, (i32, &str)> = a.pair_with::<Validated<&str, (i32, &str)>, &str>(&b);
    /// assert!(matches!(validated_pair, Validated::Valid((42, "hello"))));
    /// ```
    #[inline]
    fn pair_with<P, U>(&self, other: &U) -> P::Output<(Self, U)>
    where
        P: Pure,
        Self: Clone,
        U: Clone,
    {
        let pair = (self.clone(), other.clone());
        P::pure(&pair)
    }

    /// Lift another value into a context.
    ///
    /// This method lifts a different value into the same context type.
    /// It's useful for working with applicative functors.
    ///
    /// # Type Parameters
    ///
    /// * `P`: The higher-kinded type to lift into, implementing `Pure`
    /// * `U`: The type of the other value
    ///
    /// # Parameters
    ///
    /// * `other`: A reference to the value to lift
    ///
    /// # Returns
    ///
    /// The other value lifted into the context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::hkt::HKT;
    /// use rustica::traits::pure::{Pure, PureExt};
    ///
    /// let a: i32 = 42;
    /// let b: &str = "hello";
    ///
    /// // Lift b into the same context as would be used for a
    /// let option_b: Option<&str> = a.lift_other::<Option<&str>, &str>(&b);
    /// assert_eq!(option_b, Some("hello"));
    /// ```
    #[inline]
    fn lift_other<P, U>(&self, other: &U) -> P::Output<U>
    where
        P: Pure,
        U: Clone,
    {
        P::pure(other)
    }

    /// Combine two values into a new value and lift it into a context.
    ///
    /// This method applies a function to two values and lifts the result
    /// into a higher-kinded context. It's particularly useful for applicative-style
    /// programming.
    ///
    /// # Type Parameters
    ///
    /// * `P`: The higher-kinded type to lift into, implementing `Pure`
    /// * `U`: The type of the second value
    /// * `V`: The result type after applying the function
    ///
    /// # Parameters
    ///
    /// * `other`: A reference to the second value to combine with
    /// * `f`: The function to apply to both values
    ///
    /// # Returns
    ///
    /// The result of applying the function to both values, lifted into the context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::hkt::HKT;
    /// use rustica::traits::pure::{Pure, PureExt};
    ///
    /// let a: i32 = 42;
    /// let b: i32 = 10;
    ///
    /// // Combine values with a function
    /// let result: Option<i32> = a.combine_with::<Option<i32>, i32, i32>(&b, |x, y| *x * *y);
    /// assert_eq!(result, Some(420));
    /// ```
    #[inline]
    fn combine_with<P, U, V>(&self, other: &U, f: impl Fn(&Self, &U) -> V) -> P::Output<V>
    where
        P: Pure,
        Self: Clone,
        U: Clone,
        V: Clone,
    {
        let result = f(self, other);
        P::pure(&result)
    }
}

impl<T: Clone> PureExt for T {}

/// A zero-cost wrapper for types that implement `Pure`.
///
/// This wrapper uses `PhantomData` to avoid any runtime overhead while
/// still providing a way to specify which `Pure` implementation to use.
///
/// # Type Parameters
///
/// * `P`: The type that implements `Pure`
/// * `T`: The source type of the higher-kinded type
///
/// # Examples
///
/// ```rust
/// use rustica::traits::hkt::HKT;
/// use rustica::traits::pure::{Pure, PureType};
///
/// // Create a PureType with Option as the Pure implementation
/// let pure_option = PureType::<Option<i32>, i32>::new();
///
/// // Use it to lift values
/// let option: Option<i32> = PureType::<Option<i32>, i32>::lift(&42);
/// assert_eq!(option, Some(42));
///
/// // PureType is zero-cost - it doesn't add any runtime overhead
/// assert_eq!(std::mem::size_of::<PureType<Option<i32>, i32>>(), 0);
/// ```
///
/// Using with the Validated type:
///
/// ```rust
/// use rustica::traits::hkt::HKT;
/// use rustica::traits::pure::{Pure, PureType};
/// use rustica::datatypes::validated::Validated;
/// use rustica::traits::functor::Functor;
///
/// // Create Pure wrappers for different contexts
/// let pure_validated = PureType::<Validated<&str, i32>, i32>::new();
///
/// // Lift a value into the Validated context
/// let valid: Validated<&str, i32> = PureType::<Validated<&str, i32>, i32>::lift(&42);
///
/// // We can then use Functor operations on the result
/// let doubled: Validated<&str, i32> = valid.fmap(|x: &i32| x * 2);
/// assert!(matches!(doubled, Validated::Valid(84)));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PureType<P, T>(PhantomData<P>, PhantomData<T>);

impl<P, T> PureType<P, T>
where
    P: Pure,
{
    /// Create a new PureType.
    ///
    /// Since this type is zero-sized, this method is essentially a no-op.
    ///
    /// # Returns
    ///
    /// A new PureType instance
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::pure::PureType;
    ///
    /// let pure_option = PureType::<Option<i32>, i32>::new();
    /// ```
    #[inline]
    pub fn new() -> Self {
        PureType(PhantomData, PhantomData)
    }

    /// Lift a value into a context.
    ///
    /// This method lifts a value into the context specified by the `P` type parameter.
    ///
    /// # Type Parameters
    ///
    /// * `U`: The type of the value to lift
    ///
    /// # Parameters
    ///
    /// * `value`: A reference to the value to lift
    ///
    /// # Returns
    ///
    /// The value lifted into the context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::pure::{Pure, PureType};
    /// use rustica::datatypes::validated::Validated;
    ///
    /// let pure_validated = PureType::<Validated<&str, i32>, i32>::new();
    ///
    /// let valid: Validated<&str, i32> = PureType::<Validated<&str, i32>, i32>::lift(&42);
    /// assert!(matches!(valid, Validated::Valid(42)));
    /// ```
    #[inline]
    pub fn lift<U: Clone>(value: &U) -> P::Output<U> {
        P::pure(value)
    }

    /// Lift a value into a context, consuming the value.
    ///
    /// This method lifts a value into the context specified by the `P` type parameter,
    /// consuming the value instead of cloning it.
    ///
    /// # Type Parameters
    ///
    /// * `U`: The type of the value to lift
    ///
    /// # Parameters
    ///
    /// * `value`: The value to lift, which will be consumed
    ///
    /// # Returns
    ///
    /// The value lifted into the context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::pure::{Pure, PureType};
    /// use rustica::datatypes::validated::Validated;
    ///
    /// let pure_validated = PureType::<Validated<&str, i32>, i32>::new();
    ///
    /// let valid: Validated<&str, i32> = PureType::<Validated<&str, i32>, i32>::lift_owned(42);
    /// assert!(matches!(valid, Validated::Valid(42)));
    /// ```
    #[inline]
    pub fn lift_owned<U: Clone>(value: U) -> P::Output<U> {
        P::pure_owned(value)
    }
}

// Default implementation
impl<P: Pure, T> Default for PureType<P, T> {
    /// Create a default PureType.
    ///
    /// This method returns a new PureType instance.
    ///
    /// # Returns
    ///
    /// A new PureType instance
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::pure::PureType;
    /// use std::default::Default;
    ///
    /// let pure_option: PureType<Option<i32>, i32> = Default::default();
    /// ```
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}