ordofp_core 0.1.0

OrdoFP core provides developers with HList, Disiunctio, NominataUniversalis, Universalis, and functional type classes
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
//! Profunctor Optics - `OpticumProfunctor`
//!
//! > *"Per profundum ad veritatem"*
//! > — Through depth to truth. (Latin)
//!
//! This module provides profunctor-based optics, offering a more principled
//! and composable approach to optics based on the profunctor abstraction.
//!
//! # Overview
//!
//! Profunctor optics represent optics as transformations on profunctors,
//! enabling elegant composition and a unified representation of different
//! optic types.
//!
//! # Scholastic Naming
//!
//! | English | Latin | Etymology |
//! |---------|-------|-----------|
//! | Profunctor | Profunctor | *pro* = before + *functor* = performer |
//! | Strong | Fortis | *fortis* = strong |
//! | Choice | Electio | *electio* = choice |
//! | Optic | Opticum | *opticus* = of sight |

use core::marker::PhantomData;

/// A profunctor is a bifunctor that is contravariant in the first argument
/// and covariant in the second.
///
/// > *"Profunctor est bifunctor inversus in primo, directus in secundo."*
///
/// # Type Parameters
/// - `A` - The contravariant input type
/// - `B` - The covariant output type
pub trait Profunctor<A, B>: Sized {
    /// The result type after applying dimap
    type Mapped<C, D>: Profunctor<C, D>;

    /// Map over both type parameters.
    ///
    /// `dimap f g` is equivalent to `lmap f >>> rmap g`.
    fn dimap<C, D, F, G>(self, f: F, g: G) -> Self::Mapped<C, D>
    where
        F: Fn(C) -> A + 'static,
        G: Fn(B) -> D + 'static;

    /// Map over the left (contravariant) type parameter.
    #[inline]
    fn lmap<C, F>(self, f: F) -> Self::Mapped<C, B>
    where
        F: Fn(C) -> A + 'static,
    {
        self.dimap(f, |b| b)
    }

    /// Map over the right (covariant) type parameter.
    #[inline]
    fn rmap<D, G>(self, g: G) -> Self::Mapped<A, D>
    where
        G: Fn(B) -> D + 'static,
    {
        self.dimap(|a| a, g)
    }
}

/// A strong profunctor can pass through a product type.
///
/// > *"Fortis est qui per copulam transit."*
/// > — Strong is that which passes through a pair.
///
/// This is the characteristic of lenses.
pub trait Fortis<A, B>: Profunctor<A, B> {
    /// The result type after applying first'
    type Primus<C>: Fortis<(A, C), (B, C)>;

    /// Pass the first component through the profunctor.
    fn primus<C>(self) -> Self::Primus<C>;

    /// The result type after applying second'
    type Secundus<C>: Fortis<(C, A), (C, B)>;

    /// Pass the second component through the profunctor.
    fn secundus<C>(self) -> Self::Secundus<C>;
}

/// A choice profunctor can pass through a sum type.
///
/// > *"Electio est qui per disjunctionem transit."*
/// > — Choice is that which passes through a disjunction.
///
/// This is the characteristic of prisms.
pub trait Electio<A, B>: Profunctor<A, B> {
    /// The result type after applying left'
    type Sinister<C>: Electio<Result<A, C>, Result<B, C>>;

    /// Pass the left branch through the profunctor.
    fn sinister<C>(self) -> Self::Sinister<C>;

    /// The result type after applying right'
    type Dexter<C>: Electio<Result<C, A>, Result<C, B>>;

    /// Pass the right branch through the profunctor.
    fn dexter<C>(self) -> Self::Dexter<C>;
}

// =============================================================================
// Function Profunctor
// =============================================================================

/// A simple function profunctor.
///
/// Functions form a profunctor: `Fn(A) -> B`.
pub struct FunctioProf<A, B, F>
where
    F: Fn(A) -> B,
{
    f: F,
    _phantom: PhantomData<fn(A) -> B>,
}

impl<A, B, F> FunctioProf<A, B, F>
where
    F: Fn(A) -> B,
{
    /// Create a new function profunctor.
    #[inline]
    pub fn new(f: F) -> Self {
        FunctioProf {
            f,
            _phantom: PhantomData,
        }
    }

    /// Apply the function.
    #[inline]
    pub fn apply(&self, a: A) -> B {
        (self.f)(a)
    }
}

// =============================================================================
// Optic Types via Profunctors
// =============================================================================

/// A profunctor optic is a polymorphic function over profunctors.
///
/// > *"Opticum profunctoris est transformatio universalis."*
///
/// An optic `Optic<S, T, A, B>` transforms a `P<A, B>` into a `P<S, T>`
/// for any profunctor P satisfying certain constraints.
///
/// This encoding allows all optics to compose uniformly.
pub trait OpticumProfunctor<S, T, A, B> {
    /// Apply the optic to transform a profunctor.
    fn run<P>(&self, pab: P) -> P::Mapped<S, T>
    where
        P: Profunctor<A, B>;
}

/// An iso (isomorphism) as a profunctor optic.
///
/// An iso requires only the basic Profunctor constraint.
pub struct AequivalentiaProfunctor<S, T, A, B, Fwd, Bwd>
where
    Fwd: Fn(S) -> A,
    Bwd: Fn(B) -> T,
{
    forward: Fwd,
    backward: Bwd,
    _phantom: PhantomData<fn(S, T, A, B)>,
}

impl<S, T, A, B, Fwd, Bwd> AequivalentiaProfunctor<S, T, A, B, Fwd, Bwd>
where
    Fwd: Fn(S) -> A,
    Bwd: Fn(B) -> T,
{
    /// Create a new iso profunctor optic.
    #[inline]
    pub fn new(forward: Fwd, backward: Bwd) -> Self {
        AequivalentiaProfunctor {
            forward,
            backward,
            _phantom: PhantomData,
        }
    }

    /// Get the forward function.
    #[inline]
    pub fn forward(&self) -> &Fwd {
        &self.forward
    }

    /// Get the backward function.
    #[inline]
    pub fn backward(&self) -> &Bwd {
        &self.backward
    }
}

impl<S, T, A, B, Fwd, Bwd> Clone for AequivalentiaProfunctor<S, T, A, B, Fwd, Bwd>
where
    Fwd: Fn(S) -> A + Clone,
    Bwd: Fn(B) -> T + Clone,
{
    fn clone(&self) -> Self {
        AequivalentiaProfunctor {
            forward: self.forward.clone(),
            backward: self.backward.clone(),
            _phantom: PhantomData,
        }
    }
}

/// A lens as a profunctor optic.
///
/// A lens requires the Strong (Fortis) profunctor constraint.
pub struct AspectusProfunctor<S, T, A, B, Get, Set>
where
    Get: Fn(&S) -> A,
    Set: Fn(S, B) -> T,
{
    get: Get,
    set: Set,
    _phantom: PhantomData<fn(S, T, A, B)>,
}

impl<S, T, A, B, Get, Set> AspectusProfunctor<S, T, A, B, Get, Set>
where
    Get: Fn(&S) -> A,
    Set: Fn(S, B) -> T,
{
    /// Create a new lens profunctor optic.
    #[inline]
    pub fn new(get: Get, set: Set) -> Self {
        AspectusProfunctor {
            get,
            set,
            _phantom: PhantomData,
        }
    }

    /// Get the focused value.
    #[inline]
    pub fn view(&self, s: &S) -> A {
        (self.get)(s)
    }

    /// Set a new value.
    #[inline]
    pub fn set(&self, s: S, b: B) -> T {
        (self.set)(s, b)
    }

    /// Modify the focused value.
    #[inline]
    pub fn over<F>(&self, s: S, f: F) -> T
    where
        F: FnOnce(A) -> B,
    {
        let a = (self.get)(&s);
        (self.set)(s, f(a))
    }
}

impl<S, T, A, B, Get, Set> Clone for AspectusProfunctor<S, T, A, B, Get, Set>
where
    Get: Fn(&S) -> A + Clone,
    Set: Fn(S, B) -> T + Clone,
{
    fn clone(&self) -> Self {
        AspectusProfunctor {
            get: self.get.clone(),
            set: self.set.clone(),
            _phantom: PhantomData,
        }
    }
}

/// A prism as a profunctor optic.
///
/// A prism requires the Choice (Electio) profunctor constraint.
pub struct DivisioProfunctor<S, T, A, B, Match, Build>
where
    Match: Fn(S) -> Result<A, T>,
    Build: Fn(B) -> T,
{
    matching: Match,
    build: Build,
    _phantom: PhantomData<fn(S, T, A, B)>,
}

impl<S, T, A, B, Match, Build> DivisioProfunctor<S, T, A, B, Match, Build>
where
    Match: Fn(S) -> Result<A, T>,
    Build: Fn(B) -> T,
{
    /// Create a new prism profunctor optic.
    ///
    /// - `matching`: Returns `Ok(a)` if the prism matches, `Err(t)` otherwise
    /// - `build`: Constructs the target from the focus
    #[inline]
    pub fn new(matching: Match, build: Build) -> Self {
        DivisioProfunctor {
            matching,
            build,
            _phantom: PhantomData,
        }
    }

    /// Try to extract the focused value.
    #[inline]
    pub fn preview(&self, s: S) -> Option<A> {
        (self.matching)(s).ok()
    }

    /// Construct the target from a value.
    #[inline]
    pub fn review(&self, b: B) -> T {
        (self.build)(b)
    }

    /// Modify if the prism matches.
    #[inline]
    pub fn over<F>(&self, s: S, f: F) -> T
    where
        F: FnOnce(A) -> B,
    {
        match (self.matching)(s) {
            Ok(a) => (self.build)(f(a)),
            Err(t) => t,
        }
    }
}

impl<S, T, A, B, Match, Build> Clone for DivisioProfunctor<S, T, A, B, Match, Build>
where
    Match: Fn(S) -> Result<A, T> + Clone,
    Build: Fn(B) -> T + Clone,
{
    fn clone(&self) -> Self {
        DivisioProfunctor {
            matching: self.matching.clone(),
            build: self.build.clone(),
            _phantom: PhantomData,
        }
    }
}

// =============================================================================
// Simple (Monomorphic) Optic Type Aliases
// =============================================================================

/// A simple iso where S = T and A = B.
pub type AequivalentiaSimplexProf<S, A, Fwd, Bwd> = AequivalentiaProfunctor<S, S, A, A, Fwd, Bwd>;

/// A simple lens where S = T and A = B.
pub type AspectusSimplexProf<S, A, Get, Set> = AspectusProfunctor<S, S, A, A, Get, Set>;

/// A simple prism where S = T and A = B.
pub type DivisioSimplexProf<S, A, Match, Build> = DivisioProfunctor<S, S, A, A, Match, Build>;

// =============================================================================
// Composition
// =============================================================================

/// Variance marker tying a [`ComposedOptic`] to its six phantom type
/// parameters (`fn`-pointer encoding keeps the optic `Send`/`Sync` and
/// contravariant-safe without storing any data).
type ComposedOpticMarker<S, T, M, N, A, B> = PhantomData<fn(S, T, M, N, A, B)>;

/// Composed profunctor optic.
pub struct ComposedOptic<O1, O2, S, T, M, N, A, B>
where
    O1: Clone,
    O2: Clone,
{
    outer: O1,
    inner: O2,
    _phantom: ComposedOpticMarker<S, T, M, N, A, B>,
}

impl<O1, O2, S, T, M, N, A, B> ComposedOptic<O1, O2, S, T, M, N, A, B>
where
    O1: Clone,
    O2: Clone,
{
    /// Compose two optics.
    #[inline]
    pub fn new(outer: O1, inner: O2) -> Self {
        ComposedOptic {
            outer,
            inner,
            _phantom: PhantomData,
        }
    }
}

impl<O1, O2, S, T, M, N, A, B> Clone for ComposedOptic<O1, O2, S, T, M, N, A, B>
where
    O1: Clone,
    O2: Clone,
{
    fn clone(&self) -> Self {
        ComposedOptic {
            outer: self.outer.clone(),
            inner: self.inner.clone(),
            _phantom: PhantomData,
        }
    }
}

// =============================================================================
// Helper Functions
// =============================================================================

/// Create a simple (monomorphic) lens profunctor optic.
#[inline]
pub fn aspectus_profunctor<S, A, Get, Set>(
    get: Get,
    set: Set,
) -> AspectusSimplexProf<S, A, Get, Set>
where
    Get: Fn(&S) -> A,
    Set: Fn(S, A) -> S,
{
    AspectusProfunctor::new(get, set)
}

/// Create a polymorphic lens profunctor optic.
#[inline]
pub fn aspectus_profunctor_poly<S, T, A, B, Get, Set>(
    get: Get,
    set: Set,
) -> AspectusProfunctor<S, T, A, B, Get, Set>
where
    Get: Fn(&S) -> A,
    Set: Fn(S, B) -> T,
{
    AspectusProfunctor::new(get, set)
}

/// Create a simple (monomorphic) prism profunctor optic.
#[inline]
pub fn divisio_profunctor<S, A, Match, Build>(
    matching: Match,
    build: Build,
) -> DivisioSimplexProf<S, A, Match, Build>
where
    Match: Fn(S) -> Result<A, S>,
    Build: Fn(A) -> S,
{
    DivisioProfunctor::new(matching, build)
}

/// Create a polymorphic prism profunctor optic.
#[inline]
pub fn divisio_profunctor_poly<S, T, A, B, Match, Build>(
    matching: Match,
    build: Build,
) -> DivisioProfunctor<S, T, A, B, Match, Build>
where
    Match: Fn(S) -> Result<A, T>,
    Build: Fn(B) -> T,
{
    DivisioProfunctor::new(matching, build)
}

/// Create a simple (monomorphic) iso profunctor optic.
#[inline]
pub fn aequivalentia_profunctor<S, A, Fwd, Bwd>(
    forward: Fwd,
    backward: Bwd,
) -> AequivalentiaSimplexProf<S, A, Fwd, Bwd>
where
    Fwd: Fn(S) -> A,
    Bwd: Fn(A) -> S,
{
    AequivalentiaProfunctor::new(forward, backward)
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    extern crate alloc;
    use alloc::string::{String, ToString};

    #[derive(Clone, Debug, PartialEq)]
    struct Person {
        name: String,
        age: u32,
    }

    #[derive(Clone, Debug, PartialEq)]
    enum Shape {
        Circle(f64),
        Rectangle(f64, f64),
    }

    #[test]
    fn test_aspectus_profunctor_view() {
        let name_lens = aspectus_profunctor(
            |p: &Person| p.name.clone(),
            |p: Person, name| Person { name, age: p.age },
        );

        let person = Person {
            name: "Alice".to_string(),
            age: 30,
        };

        assert_eq!(name_lens.view(&person), "Alice");
    }

    #[test]
    fn test_aspectus_profunctor_set() {
        let name_lens = aspectus_profunctor(
            |p: &Person| p.name.clone(),
            |p: Person, name| Person { name, age: p.age },
        );

        let person = Person {
            name: "Alice".to_string(),
            age: 30,
        };

        let updated = name_lens.set(person, "Bob".to_string());
        assert_eq!(updated.name, "Bob");
        assert_eq!(updated.age, 30);
    }

    #[test]
    fn test_aspectus_profunctor_over() {
        let name_lens = aspectus_profunctor(
            |p: &Person| p.name.clone(),
            |p: Person, name| Person { name, age: p.age },
        );

        let person = Person {
            name: "Alice".to_string(),
            age: 30,
        };

        let modified = name_lens.over(person, |n| n.to_uppercase());
        assert_eq!(modified.name, "ALICE");
    }

    #[test]
    fn test_divisio_profunctor_preview() {
        let circle_prism = divisio_profunctor(
            |s: Shape| match s {
                Shape::Circle(r) => Ok(r),
                other => Err(other),
            },
            Shape::Circle,
        );

        let circle = Shape::Circle(5.0);
        let rect = Shape::Rectangle(3.0, 4.0);

        assert_eq!(circle_prism.preview(circle), Some(5.0));
        assert_eq!(circle_prism.preview(rect), None);
    }

    #[test]
    fn test_divisio_profunctor_review() {
        let circle_prism = divisio_profunctor(
            |s: Shape| match s {
                Shape::Circle(r) => Ok(r),
                other => Err(other),
            },
            Shape::Circle,
        );

        assert_eq!(circle_prism.review(10.0), Shape::Circle(10.0));
    }

    #[test]
    fn test_divisio_profunctor_over() {
        let circle_prism = divisio_profunctor(
            |s: Shape| match s {
                Shape::Circle(r) => Ok(r),
                other => Err(other),
            },
            Shape::Circle,
        );

        let circle = Shape::Circle(5.0);
        let rect = Shape::Rectangle(3.0, 4.0);

        let doubled = circle_prism.over(circle, |r| r * 2.0);
        assert_eq!(doubled, Shape::Circle(10.0));

        let unchanged = circle_prism.over(rect.clone(), |r| r * 2.0);
        assert_eq!(unchanged, rect);
    }

    #[test]
    fn test_aequivalentia_profunctor() {
        let swap_iso = aequivalentia_profunctor(
            |(a, b): (i32, String)| (b, a),
            |(b, a): (String, i32)| (a, b),
        );

        let original = (42, "hello".to_string());
        let swapped = (swap_iso.forward())(original.clone());
        assert_eq!(swapped, ("hello".to_string(), 42));

        let back = (swap_iso.backward())(swapped);
        assert_eq!(back, original);
    }

    #[test]
    fn test_polymorphic_lens() {
        // A lens that can change the type: Person -> PersonWithNickname
        #[derive(Clone, Debug, PartialEq)]
        struct PersonWithNickname {
            name: String,
            nickname: String,
            age: u32,
        }

        let poly_lens = aspectus_profunctor_poly(
            |p: &Person| p.name.clone(),
            |p: Person, nickname: String| PersonWithNickname {
                name: p.name,
                nickname,
                age: p.age,
            },
        );

        let person = Person {
            name: "Alice".to_string(),
            age: 30,
        };

        let with_nickname = poly_lens.set(person, "Ali".to_string());
        assert_eq!(with_nickname.name, "Alice");
        assert_eq!(with_nickname.nickname, "Ali");
        assert_eq!(with_nickname.age, 30);
    }
}