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
//! Aspectus (Lens) - Focus on a single field within a product type (struct).
//!
//! > *"Aspectus est actus intellectus quo rem intuetur."*
//! > — An aspect is the act of the intellect by which it beholds a thing. (Scholastic)
//!
//! An aspectus provides a way to:
//! - **Get** a value from a larger structure
//! - **Set** a value within a larger structure (returning a new structure)
//! - **Modify** a value using a function (returning a new structure)
//!
//! Aspectus are composable, allowing you to focus on deeply nested data.

/// An aspectus (lens) focusing on a value of type `A` within a structure of type `S`.
///
/// An aspectus is defined by two functions:
/// - `get: &S -> A` - Extract the focused value
/// - `set: (&S, A) -> S` - Set a new value, returning a new structure
///
/// # Type Parameters
/// - `S` - The source/whole type
/// - `A` - The target/part type
/// - `GetFn` - The getter function type
/// - `SetFn` - The setter function type
pub struct Aspectus<S, A, GetFn, SetFn>
where
    GetFn: Fn(&S) -> A,
    SetFn: Fn(&S, A) -> S,
{
    get_fn: GetFn,
    set_fn: SetFn,
    _phantom: core::marker::PhantomData<fn(&S) -> A>,
}

impl<S, A, GetFn, SetFn> Clone for Aspectus<S, A, GetFn, SetFn>
where
    GetFn: Fn(&S) -> A + Clone,
    SetFn: Fn(&S, A) -> S + Clone,
{
    fn clone(&self) -> Self {
        Self {
            get_fn: self.get_fn.clone(),
            set_fn: self.set_fn.clone(),
            _phantom: core::marker::PhantomData,
        }
    }
}

impl<S, A, GetFn, SetFn> Aspectus<S, A, GetFn, SetFn>
where
    GetFn: Fn(&S) -> A,
    SetFn: Fn(&S, A) -> S,
{
    /// Create a new aspectus from getter and setter functions.
    ///
    /// # Arguments
    /// - `get_fn` - Function to extract the focused value from the structure
    /// - `set_fn` - Function to set a new value in the structure
    ///
    /// # Example
    ///
    /// ```rust
    /// use ordofp_core::optics::Aspectus;
    ///
    /// #[derive(Clone)]
    /// struct Point { x: i32, y: i32 }
    ///
    /// let x_aspectus = Aspectus::new(
    ///     |p: &Point| p.x,
    ///     |p: &Point, x: i32| Point { x, y: p.y },
    /// );
    ///
    /// let point = Point { x: 10, y: 20 };
    /// assert_eq!(x_aspectus.get(&point), 10);
    /// ```
    #[inline]
    pub fn new(get_fn: GetFn, set_fn: SetFn) -> Self {
        Self {
            get_fn,
            set_fn,
            _phantom: core::marker::PhantomData,
        }
    }

    /// Extract the focused value from the structure.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ordofp_core::optics::aspectus;
    ///
    /// #[derive(Clone)]
    /// struct Point { x: i32, y: i32 }
    ///
    /// let x_aspectus = aspectus(
    ///     |p: &Point| p.x,
    ///     |p: &Point, x: i32| Point { x, y: p.y },
    /// );
    ///
    /// let point = Point { x: 10, y: 20 };
    /// assert_eq!(x_aspectus.get(&point), 10);
    /// ```
    #[inline]
    pub fn get(&self, source: &S) -> A {
        (self.get_fn)(source)
    }

    /// Set a new value for the focused part, returning a new structure.
    ///
    /// This does not modify the original structure.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ordofp_core::optics::aspectus;
    ///
    /// #[derive(Clone, Debug, PartialEq)]
    /// struct Point { x: i32, y: i32 }
    ///
    /// let x_aspectus = aspectus(
    ///     |p: &Point| p.x,
    ///     |p: &Point, x: i32| Point { x, y: p.y },
    /// );
    ///
    /// let point = Point { x: 10, y: 20 };
    /// let updated = x_aspectus.set(&point, 100);
    ///
    /// assert_eq!(updated, Point { x: 100, y: 20 });
    /// assert_eq!(point.x, 10); // Original unchanged
    /// ```
    #[inline]
    pub fn set(&self, source: &S, value: A) -> S {
        (self.set_fn)(source, value)
    }

    /// Modify the focused value using a function, returning a new structure.
    ///
    /// Equivalent to `aspectus.set(source, f(aspectus.get(source)))`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ordofp_core::optics::aspectus;
    ///
    /// #[derive(Clone, Debug, PartialEq)]
    /// struct Point { x: i32, y: i32 }
    ///
    /// let x_aspectus = aspectus(
    ///     |p: &Point| p.x,
    ///     |p: &Point, x: i32| Point { x, y: p.y },
    /// );
    ///
    /// let point = Point { x: 10, y: 20 };
    /// let doubled = x_aspectus.modify(&point, |x| x * 2);
    ///
    /// assert_eq!(doubled, Point { x: 20, y: 20 });
    /// ```
    #[inline]
    pub fn modify<F>(&self, source: &S, f: F) -> S
    where
        F: FnOnce(A) -> A,
    {
        let value = self.get(source);
        self.set(source, f(value))
    }

    /// Compose this aspectus with another aspectus to focus on nested data.
    ///
    /// If `self` focuses on `A` within `S`, and `other` focuses on `B` within `A`,
    /// the composed aspectus focuses on `B` within `S`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ordofp_core::optics::aspectus;
    ///
    /// #[derive(Clone, Debug, PartialEq)]
    /// struct Address { street: String, city: String }
    ///
    /// #[derive(Clone, Debug, PartialEq)]
    /// struct Person { name: String, address: Address }
    ///
    /// let address_aspectus = aspectus(
    ///     |p: &Person| p.address.clone(),
    ///     |p: &Person, a: Address| Person { name: p.name.clone(), address: a },
    /// );
    ///
    /// let street_aspectus = aspectus(
    ///     |a: &Address| a.street.clone(),
    ///     |a: &Address, s: String| Address { street: s, city: a.city.clone() },
    /// );
    ///
    /// let person_street = address_aspectus.compose(&street_aspectus);
    ///
    /// let person = Person {
    ///     name: "Alice".to_string(),
    ///     address: Address {
    ///         street: "123 Main St".to_string(),
    ///         city: "Springfield".to_string(),
    ///     },
    /// };
    ///
    /// assert_eq!(person_street.get(&person), "123 Main St");
    /// ```
    #[inline]
    pub fn compose<B, GetFn2, SetFn2>(
        &self,
        other: &Aspectus<A, B, GetFn2, SetFn2>,
    ) -> ComposedAspectus<S, A, B, GetFn, SetFn, GetFn2, SetFn2>
    where
        GetFn: Clone,
        SetFn: Clone,
        GetFn2: Fn(&A) -> B + Clone,
        SetFn2: Fn(&A, B) -> A + Clone,
    {
        ComposedAspectus {
            outer: self.clone(),
            inner: other.clone(),
        }
    }
}

/// A composed aspectus focusing on `B` within `S` through an intermediate `A`.
#[derive(Clone)]
pub struct ComposedAspectus<S, A, B, GetFn1, SetFn1, GetFn2, SetFn2>
where
    GetFn1: Fn(&S) -> A,
    SetFn1: Fn(&S, A) -> S,
    GetFn2: Fn(&A) -> B,
    SetFn2: Fn(&A, B) -> A,
{
    outer: Aspectus<S, A, GetFn1, SetFn1>,
    inner: Aspectus<A, B, GetFn2, SetFn2>,
}

impl<S, A, B, GetFn1, SetFn1, GetFn2, SetFn2>
    ComposedAspectus<S, A, B, GetFn1, SetFn1, GetFn2, SetFn2>
where
    GetFn1: Fn(&S) -> A,
    SetFn1: Fn(&S, A) -> S,
    GetFn2: Fn(&A) -> B,
    SetFn2: Fn(&A, B) -> A,
{
    /// Extract the focused value from the structure.
    #[inline]
    pub fn get(&self, source: &S) -> B {
        let a = self.outer.get(source);
        self.inner.get(&a)
    }

    /// Set a new value for the focused part, returning a new structure.
    #[inline]
    pub fn set(&self, source: &S, value: B) -> S {
        let a = self.outer.get(source);
        let new_a = self.inner.set(&a, value);
        self.outer.set(source, new_a)
    }

    /// Modify the focused value using a function, returning a new structure.
    #[inline]
    pub fn modify<F>(&self, source: &S, f: F) -> S
    where
        F: FnOnce(B) -> B,
    {
        let a = self.outer.get(source);
        let b = self.inner.get(&a);
        let new_b = f(b);
        let new_a = self.inner.set(&a, new_b);
        self.outer.set(source, new_a)
    }
}

/// Create a new aspectus from getter and setter functions.
///
/// This is a convenience function equivalent to `Aspectus::new`.
///
/// # Example
///
/// ```rust
/// use ordofp_core::optics::aspectus;
///
/// #[derive(Clone, Debug, PartialEq)]
/// struct Point { x: i32, y: i32 }
///
/// let x_aspectus = aspectus(
///     |p: &Point| p.x,
///     |p: &Point, x: i32| Point { x, y: p.y },
/// );
///
/// let point = Point { x: 10, y: 20 };
/// assert_eq!(x_aspectus.get(&point), 10);
/// assert_eq!(x_aspectus.set(&point, 100), Point { x: 100, y: 20 });
/// ```
#[inline]
pub fn aspectus<S, A, GetFn, SetFn>(get_fn: GetFn, set_fn: SetFn) -> Aspectus<S, A, GetFn, SetFn>
where
    GetFn: Fn(&S) -> A,
    SetFn: Fn(&S, A) -> S,
{
    Aspectus::new(get_fn, set_fn)
}

/// An aspectus that works with references, avoiding cloning.
///
/// This is useful when you only need to read values and don't need to modify them.
pub struct AspectusRef<S, A, GetFn>
where
    GetFn: Fn(&S) -> &A,
{
    get_fn: GetFn,
    // `fn(&S) -> &A` is always `Clone`/`Copy`, so (unlike `PhantomData<(S, A)>`
    // with `#[derive(Clone)]`) cloning does not spuriously require `S: Clone`.
    _phantom: core::marker::PhantomData<fn(&S) -> &A>,
}

impl<S, A, GetFn> Clone for AspectusRef<S, A, GetFn>
where
    GetFn: Fn(&S) -> &A + Clone,
{
    #[inline]
    fn clone(&self) -> Self {
        Self {
            get_fn: self.get_fn.clone(),
            _phantom: core::marker::PhantomData,
        }
    }
}

impl<S, A, GetFn> AspectusRef<S, A, GetFn>
where
    GetFn: Fn(&S) -> &A,
{
    /// Create a new reference aspectus.
    #[inline]
    pub fn new(get_fn: GetFn) -> Self {
        Self {
            get_fn,
            _phantom: core::marker::PhantomData,
        }
    }

    /// Get a reference to the focused value.
    #[inline]
    pub fn get<'a>(&self, source: &'a S) -> &'a A {
        (self.get_fn)(source)
    }

    /// Compose with another reference aspectus to focus on nested data, reading
    /// through both levels **without cloning** any intermediate.
    ///
    /// If `self` focuses on `&A` within `S`, and `other` focuses on `&B` within
    /// `A`, the composed reference aspectus reads `&B` from `&S` directly.
    /// Unlike the owning [`Aspectus::compose`], no intermediate `A` is cloned —
    /// the read is a pure pointer chase.
    ///
    /// # Example
    ///
    /// ```rust
    /// use ordofp_core::optics::AspectusRef;
    ///
    /// struct Course { name: String }
    /// struct Enrollment { course: Course }
    ///
    /// let course = AspectusRef::new(|e: &Enrollment| &e.course);
    /// let name = AspectusRef::new(|c: &Course| &c.name);
    /// let course_name = course.compose(&name);
    ///
    /// let e = Enrollment { course: Course { name: "FP".to_string() } };
    /// assert_eq!(course_name.get(&e), "FP"); // no clone of Course or name
    /// ```
    #[inline]
    pub fn compose<B, GetFn2>(
        &self,
        other: &AspectusRef<A, B, GetFn2>,
    ) -> ComposedAspectusRef<S, A, B, GetFn, GetFn2>
    where
        GetFn: Clone,
        GetFn2: Fn(&A) -> &B + Clone,
    {
        ComposedAspectusRef {
            outer: self.clone(),
            inner: other.clone(),
        }
    }
}

/// A composed reference aspectus focusing on `&B` within `S` through an
/// intermediate `A`, reading with **zero clones** (each level returns a borrow).
pub struct ComposedAspectusRef<S, A, B, GetFn1, GetFn2>
where
    GetFn1: Fn(&S) -> &A,
    GetFn2: Fn(&A) -> &B,
{
    outer: AspectusRef<S, A, GetFn1>,
    inner: AspectusRef<A, B, GetFn2>,
}

impl<S, A, B, GetFn1, GetFn2> Clone for ComposedAspectusRef<S, A, B, GetFn1, GetFn2>
where
    GetFn1: Fn(&S) -> &A + Clone,
    GetFn2: Fn(&A) -> &B + Clone,
{
    #[inline]
    fn clone(&self) -> Self {
        Self {
            outer: self.outer.clone(),
            inner: self.inner.clone(),
        }
    }
}

impl<S, A, B, GetFn1, GetFn2> ComposedAspectusRef<S, A, B, GetFn1, GetFn2>
where
    GetFn1: Fn(&S) -> &A,
    GetFn2: Fn(&A) -> &B,
{
    /// Read a reference to the deeply-focused value without cloning.
    ///
    /// `A: 'a` simply states the intermediate outlives the borrow — always true,
    /// since the reference being returned is reached through a live `&'a A`.
    #[inline]
    pub fn get<'a>(&self, source: &'a S) -> &'a B
    where
        A: 'a,
    {
        self.inner.get(self.outer.get(source))
    }
}

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

    #[derive(Clone, Debug, PartialEq)]
    struct Point {
        x: i32,
        y: i32,
    }

    #[derive(Clone, Debug, PartialEq)]
    struct Line {
        start: Point,
        end: Point,
    }

    #[test]
    fn test_aspectus_basic() {
        let x_aspectus = aspectus(|p: &Point| p.x, |p: &Point, x: i32| Point { x, y: p.y });

        let point = Point { x: 10, y: 20 };
        assert_eq!(x_aspectus.get(&point), 10);
        assert_eq!(x_aspectus.set(&point, 100), Point { x: 100, y: 20 });
        assert_eq!(x_aspectus.modify(&point, |x| x + 5), Point { x: 15, y: 20 });
    }

    #[test]
    fn test_aspectus_composition() {
        let start_aspectus = aspectus(
            |l: &Line| l.start.clone(),
            |l: &Line, start: Point| Line {
                start,
                end: l.end.clone(),
            },
        );

        let x_aspectus = aspectus(|p: &Point| p.x, |p: &Point, x: i32| Point { x, y: p.y });

        let start_x = start_aspectus.compose(&x_aspectus);

        let line = Line {
            start: Point { x: 0, y: 0 },
            end: Point { x: 10, y: 10 },
        };

        assert_eq!(start_x.get(&line), 0);
        assert_eq!(
            start_x.set(&line, 5),
            Line {
                start: Point { x: 5, y: 0 },
                end: Point { x: 10, y: 10 },
            }
        );
    }

    #[test]
    fn test_aspectus_ref() {
        let x_ref = AspectusRef::new(|p: &Point| &p.x);

        let point = Point { x: 10, y: 20 };
        assert_eq!(*x_ref.get(&point), 10);
    }

    #[test]
    fn test_aspectus_ref_compose_zero_clone() {
        // Composed reference aspectus reads nested data without cloning the
        // intermediate (the whole point of F1). Line -> start (Point) -> x.
        let start_ref = AspectusRef::new(|l: &Line| &l.start);
        let x_ref = AspectusRef::new(|p: &Point| &p.x);
        let start_x = start_ref.compose(&x_ref);

        let line = Line {
            start: Point { x: 3, y: 7 },
            end: Point { x: 10, y: 10 },
        };

        // Reads return a borrow that points into `line` — proving no intermediate
        // Point was cloned (the address must be inside `line`).
        let got: &i32 = start_x.get(&line);
        assert_eq!(*got, 3);
        assert!(core::ptr::eq(got, &raw const line.start.x));
    }

    #[test]
    fn test_aspectus_ref_compose_is_clone() {
        // The composed reference aspectus is Clone (needed to store/reuse it),
        // and cloning does not require S/A/B: Clone.
        let start_ref = AspectusRef::new(|l: &Line| &l.start);
        let x_ref = AspectusRef::new(|p: &Point| &p.x);
        let start_x = start_ref.compose(&x_ref);
        let cloned = start_x.clone();

        let line = Line {
            start: Point { x: 9, y: 1 },
            end: Point { x: 2, y: 2 },
        };
        assert_eq!(*cloned.get(&line), 9);
    }

    #[test]
    fn test_composed_aspectus_modify() {
        // ComposedAspectus::modify follows a distinct code path from set/get and
        // was previously untested. Verify it correctly threads the transformation
        // through both lenses without touching unrelated fields.
        let start_aspectus = aspectus(
            |l: &Line| l.start.clone(),
            |l: &Line, start: Point| Line {
                start,
                end: l.end.clone(),
            },
        );
        let x_aspectus = aspectus(|p: &Point| p.x, |p: &Point, x: i32| Point { x, y: p.y });
        let start_x = start_aspectus.compose(&x_aspectus);

        let line = Line {
            start: Point { x: 3, y: 7 },
            end: Point { x: 10, y: 10 },
        };

        let result = start_x.modify(&line, |x| x * 2);

        assert_eq!(result.start.x, 6, "focused field should be doubled");
        assert_eq!(
            result.start.y, 7,
            "non-focused field in inner struct must be unchanged"
        );
        assert_eq!(
            result.end, line.end,
            "non-focused field in outer struct must be unchanged"
        );
    }
}