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
//! Comonad type class - dual of Monad.
//!
//! > *\"Omnis effectus sufficientem rationem habet a qua dependet.\"*
//! > — Every effect has a sufficient reason on which it depends. (Leibniz)
//!
//! While `Monad` wraps values in context and chains computations,
//! `Comonad` extracts values and extends computations.
//!
//! # Scholastic Names
//!
//! - `Identitas` (Identity) - the simple identity comonad
//! - `Thesaurus` (Store) - a storehouse of values indexed by position
//! - `Contextus` (Env) - value with read-only context/environment
//! - `Vestigium` (Traced) - value with write-only trace
//!
//! # Example
//!
//! ```rust
//! use ordofp_core::comonad::{Comonad, Identitas};
//!
//! // Identitas is the simplest comonad: extract unwraps the value,
//! // extend applies a whole-context function and rewraps the result.
//! let w = Identitas(21);
//! assert_eq!(w.extract(), 21);
//!
//! let doubled = w.extend(|w| w.extract() * 2);
//! assert_eq!(doubled.extract(), 42);
//! ```
//!
//! # Laws
//!
//! 1. **Left identity**: `w.extend(extract) == w`
//! 2. **Right identity**: `w.extend(f).extract() == f(w)`
//! 3. **Associativity**: `w.extend(f).extend(g) == w.extend(|w| g(w.extend(f)))`

/// Comonad - the categorical dual of Monad.
///
/// While Monad has:
/// - `pure: A -> M<A>` (wrap a value)
/// - `flat_map: M<A> -> (A -> M<B>) -> M<B>` (chain computations)
///
/// Comonad has:
/// - `extract: W<A> -> A` (unwrap a value)
/// - `extend: W<A> -> (W<A> -> B) -> W<B>` (extend computations)
///
/// # Intuition
///
/// A comonad represents a value in a context. `extract` gets the focused value,
/// while `extend` applies a function to all possible "focus points".
pub trait Comonad: Sized {
    /// The type inside the comonad.
    type Item;

    /// Extract the focused value from the comonad.
    ///
    /// This is the dual of `pure` - instead of wrapping a value,
    /// it unwraps/extracts the focused value.
    fn extract(&self) -> Self::Item;

    /// Extend a function over the comonad.
    ///
    /// Given a function that takes the whole comonad and produces a value,
    /// apply it to all possible focus points.
    ///
    /// This is the dual of `flat_map`.
    fn extend<F, B>(&self, f: F) -> Self::Output<B>
    where
        F: Fn(&Self) -> B;

    /// Output type constructor for extend.
    type Output<B>;

    /// Duplicate the comonad.
    ///
    /// Creates a comonad of comonads where each position contains
    /// the original comonad focused at that position.
    ///
    /// `duplicate` can be defined in terms of `extend`:
    /// `w.duplicate() == w.extend(|x| x.clone())`
    #[inline]
    fn duplicate(&self) -> Self::Output<Self>
    where
        Self: Clone,
    {
        self.extend(core::clone::Clone::clone)
    }

    /// Map a function over the comonad.
    ///
    /// Every comonad is also a functor:
    /// `w.map(f) == w.extend(|w| f(w.extract()))`
    #[inline]
    fn cmap<F, B>(&self, f: F) -> Self::Output<B>
    where
        F: Fn(Self::Item) -> B,
    {
        self.extend(move |w| f(w.extract()))
    }
}

/// Identitas: A simple identity comonad wrapper.
///
/// > *\"Idem est idem sibi.\"*
/// > — The same is the same to itself. (Scholastic axiom)
///
/// The simplest comonad - just a wrapper around a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Identitas<A>(pub A);

impl<A> Identitas<A> {
    /// Create a new Identitas.
    #[inline]
    pub fn new(value: A) -> Self {
        Identitas(value)
    }

    /// Get the inner value.
    #[inline]
    pub fn value(&self) -> &A {
        &self.0
    }

    /// Into the inner value.
    #[inline]
    pub fn into_value(self) -> A {
        self.0
    }
}

impl<A: Clone> Comonad for Identitas<A> {
    type Item = A;
    type Output<B> = Identitas<B>;

    #[inline]
    fn extract(&self) -> A {
        self.0.clone()
    }

    #[inline]
    fn extend<F, B>(&self, f: F) -> Identitas<B>
    where
        F: Fn(&Self) -> B,
    {
        Identitas(f(self))
    }
}

/// Thesaurus: Store comonad - represents a value that depends on a position.
///
/// > *\"Thesaurus est locus in quo divitiae reponuntur.\"*
/// > — A storehouse is a place where riches are deposited.
///
/// This is a more interesting comonad that represents a value at a
/// position, where you can peek at other positions.
#[derive(Clone)]
pub struct Thesaurus<S, A, F>
where
    F: Fn(&S) -> A,
{
    /// The current position.
    pub position: S,
    /// Function to get value at any position.
    pub peek_fn: F,
}

impl<S: Clone, A, F> Thesaurus<S, A, F>
where
    F: Fn(&S) -> A,
{
    /// Create a new Thesaurus.
    #[inline]
    pub fn new(position: S, peek_fn: F) -> Self {
        Thesaurus { position, peek_fn }
    }

    /// Peek at a specific position.
    #[inline]
    pub fn peek(&self, pos: &S) -> A {
        (self.peek_fn)(pos)
    }

    /// Get the current position.
    #[inline]
    pub fn pos(&self) -> &S {
        &self.position
    }

    /// Move to a new position.
    #[inline]
    pub fn seek(self, new_pos: S) -> Self {
        Thesaurus {
            position: new_pos,
            peek_fn: self.peek_fn,
        }
    }

    /// Modify the position.
    #[inline]
    pub fn seeks<G>(self, f: G) -> Self
    where
        G: FnOnce(S) -> S,
    {
        Thesaurus {
            position: f(self.position),
            peek_fn: self.peek_fn,
        }
    }
}

/// Contextus: Env comonad - value with read-only environment.
///
/// > *\"Contextus dat intellectum verbis.\"*
/// > — Context gives understanding to words.
///
/// This is a simple comonad where each value has an associated environment.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Contextus<E, A> {
    /// The environment.
    pub env: E,
    /// The value.
    pub value: A,
}

impl<E, A> Contextus<E, A> {
    /// Create a new Contextus.
    #[inline]
    pub fn new(env: E, value: A) -> Self {
        Contextus { env, value }
    }

    /// Get the environment.
    #[inline]
    pub fn ask(&self) -> &E {
        &self.env
    }

    /// Get the value.
    #[inline]
    pub fn val(&self) -> &A {
        &self.value
    }
}

impl<E: Clone, A: Clone> Comonad for Contextus<E, A> {
    type Item = A;
    type Output<B> = Contextus<E, B>;

    #[inline]
    fn extract(&self) -> A {
        self.value.clone()
    }

    #[inline]
    fn extend<F, B>(&self, f: F) -> Contextus<E, B>
    where
        F: Fn(&Self) -> B,
    {
        Contextus {
            env: self.env.clone(),
            value: f(self),
        }
    }
}

/// Vestigium: Traced comonad - value with write-only trace.
///
/// > *\"Vestigium est signum rei praeteritae.\"*
/// > — A trace is a sign of something past.
///
/// This is dual to Reader - instead of reading from environment,
/// we accumulate a trace.
#[derive(Clone)]
pub struct Vestigium<M, A, F>
where
    F: Fn(&M) -> A,
{
    /// Function from trace to value.
    pub run: F,
    _marker: core::marker::PhantomData<M>,
}

impl<M, A, F> Vestigium<M, A, F>
where
    F: Fn(&M) -> A,
{
    /// Create a new Vestigium.
    #[inline]
    pub fn new(run: F) -> Self {
        Vestigium {
            run,
            _marker: core::marker::PhantomData,
        }
    }

    /// Run with a trace.
    #[inline]
    pub fn run_traced(&self, trace: &M) -> A {
        (self.run)(trace)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    extern crate std;
    use std::string::{String, ToString};

    #[test]
    fn test_identitas_extract() {
        let id = Identitas::new(42);
        assert_eq!(id.extract(), 42);
    }

    #[test]
    fn test_identitas_extend() {
        let id = Identitas::new(10);
        let result = id.extend(|w| w.extract() * 2);
        assert_eq!(result.extract(), 20);
    }

    #[test]
    fn test_identitas_duplicate() {
        let id = Identitas::new(42);
        let dup = id.duplicate();
        assert_eq!(dup.extract().extract(), 42);
    }

    #[test]
    fn test_identitas_cmap() {
        let id = Identitas::new(5);
        let result = id.cmap(|x| x * 3);
        assert_eq!(result.extract(), 15);
    }

    #[test]
    fn test_identitas_left_identity_law() {
        // w.extend(extract) == w
        let w = Identitas::new(42);
        let result = w.extend(super::Comonad::extract);
        assert_eq!(result.extract(), w.extract());
    }

    #[test]
    fn test_identitas_right_identity_law() {
        // w.extend(f).extract() == f(w)
        let w = Identitas::new(10);
        let f = |x: &Identitas<i32>| x.extract() * 2;
        assert_eq!(w.extend(f).extract(), f(&w));
    }

    #[test]
    fn test_contextus_extract() {
        let e = Contextus::new("config", 42);
        assert_eq!(e.extract(), 42);
    }

    #[test]
    fn test_contextus_ask() {
        let e = Contextus::new("config", 42);
        assert_eq!(e.ask(), &"config");
    }

    #[test]
    fn test_contextus_extend() {
        let e = Contextus::new(10, 5);
        // Use the environment in the computation
        let result = e.extend(|w| w.extract() + *w.ask());
        assert_eq!(result.extract(), 15);
        assert_eq!(result.ask(), &10); // Environment preserved
    }

    #[test]
    fn test_contextus_left_identity_law() {
        let w = Contextus::new("env", 42);
        let result = w.extend(super::Comonad::extract);
        assert_eq!(result.extract(), w.extract());
    }

    #[test]
    fn test_thesaurus_peek() {
        let store = Thesaurus::new(0, |i: &i32| i * i);
        assert_eq!(store.peek(&0), 0);
        assert_eq!(store.peek(&5), 25);
        assert_eq!(store.peek(&-3), 9);
    }

    #[test]
    fn test_thesaurus_seek() {
        let store = Thesaurus::new(0, |i: &i32| i * 2);
        let moved = store.seek(5);
        assert_eq!(moved.pos(), &5);
        assert_eq!(moved.peek(&5), 10);
    }

    #[test]
    fn test_thesaurus_seeks() {
        let store = Thesaurus::new(5, |i: &i32| i * 2);
        let modified = store.seeks(|x| x + 3);
        assert_eq!(modified.pos(), &8);
    }

    #[test]
    fn test_vestigium_run() {
        let traced = Vestigium::new(|s: &String| s.len());
        assert_eq!(traced.run_traced(&"hello".to_string()), 5);
        assert_eq!(traced.run_traced(&"hi".to_string()), 2);
    }
}