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
//! # `ContinuatioT` (Continuation Monad)
//!
//! `ContinuatioT<R, A>` is a plain continuation monad in
//! continuation-passing style. Despite the `T` suffix, it does **not**
//! currently layer over a base monad `M` (there is no `M` type parameter) —
//! it is `Cont`, not a true `ContT`; the name is kept for forward
//! compatibility with a future transformer version.
//!
//! ## Quick Start
//!
//! Control program flow with continuations:
//!
//! ```rust
//! use ordofp_core::transformers::ContinuatioT;
//!
//! // Create a simple continuation
//! let cont = ContinuatioT::<i32, i32>::pure(42);
//!
//! // Run the continuation with an identity function
//! let result = cont.run(|x| x);
//! assert_eq!(result, 42);
//!
//! // Chain continuations with bind
//! let chained = ContinuatioT::<i32, i32>::pure(10)
//!     .bind(|x| ContinuatioT::pure(x + 5))
//!     .bind(|x| ContinuatioT::pure(x * 2));
//!
//! let final_result = chained.run(|x| x);
//! assert_eq!(final_result, 30); // ((10 + 5) * 2)
//! ```
//!
//! ## Core Concepts
//!
//! - **Continuation-Passing Style**: Functions receive an explicit continuation
//! - **Explicit Control Flow**: Implements patterns like early exit or backtracking
//! - **Composable Computations**: Continuations can be composed using monadic operations
//!
//! ## Scholastic Naming
//!
//! Following `OrdoFP`'s Scholastic naming convention:
//! - `ContinuatioT` - Latin form of "continuation transformer"
//! - `exsequi` - Latin for "to execute/run"

use alloc::sync::Arc;
use core::marker::PhantomData;

/// Type alias for the core continuation function type.
pub(crate) type ContFn<R, A> = dyn Fn(Arc<dyn Fn(A) -> R + Send + Sync>) -> R + Send + Sync;

/// The continuation monad transformer.
///
/// `ContinuatioT<R, A>` represents a computation that takes a continuation
/// (a function from `A` to `R`) and produces a result of type `R`.
///
/// # Type Parameters
///
/// * `R` - The final result type
/// * `A` - The intermediate value type
///
/// # Examples
///
/// ```rust
/// use ordofp_core::transformers::ContinuatioT;
///
/// // Create two continuations
/// let cont1 = ContinuatioT::<i32, i32>::pure(5);
/// let cont2 = ContinuatioT::<i32, i32>::pure(-1);
///
/// // Run the continuations
/// let result1 = cont1.run(|x| x);
/// let result2 = cont2.run(|x| x);
///
/// assert_eq!(result1, 5);
/// assert_eq!(result2, -1);
/// ```
pub struct ContinuatioT<R, A> {
    run_cont: Arc<ContFn<R, A>>,
    _phantom: PhantomData<(R, A)>,
}

impl<R, A> Clone for ContinuatioT<R, A> {
    fn clone(&self) -> Self {
        ContinuatioT {
            run_cont: self.run_cont.clone(),
            _phantom: PhantomData,
        }
    }
}

impl<R: 'static, A: 'static> ContinuatioT<R, A> {
    /// Creates a new continuation from a function.
    ///
    /// # Arguments
    ///
    /// * `f` - A function that takes a continuation and returns a result
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use ordofp_core::transformers::ContinuatioT;
    ///
    /// // Create a continuation that doubles its input and adds 1
    /// let cont = ContinuatioT::new(|k: Arc<dyn Fn(i32) -> i32 + Send + Sync>| {
    ///     let x = 5;
    ///     let doubled = x * 2;
    ///     k(doubled + 1)
    /// });
    ///
    /// // Run with identity
    /// let result = cont.run(|x| x);
    /// assert_eq!(result, 11);
    /// ```
    #[inline]
    pub fn new<F>(f: F) -> Self
    where
        F: Fn(Arc<dyn Fn(A) -> R + Send + Sync>) -> R + Send + Sync + 'static,
    {
        ContinuatioT {
            run_cont: Arc::new(f),
            _phantom: PhantomData,
        }
    }

    /// Runs the continuation with the given continuation function.
    ///
    /// Named `exsequi` (Latin for "to execute") in Scholastic style.
    ///
    /// # Arguments
    ///
    /// * `k` - A function that takes a value of type `A` and returns type `R`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ordofp_core::transformers::ContinuatioT;
    ///
    /// let cont = ContinuatioT::<i32, i32>::pure(42);
    /// let result = cont.exsequi(|x| x * 2);
    /// assert_eq!(result, 84);
    /// ```
    #[inline]
    pub fn exsequi<F>(&self, k: F) -> R
    where
        F: Fn(A) -> R + Send + Sync + 'static,
    {
        (self.run_cont)(Arc::new(k))
    }

    /// Alias for `exsequi`.
    #[inline]
    pub fn run<F>(&self, k: F) -> R
    where
        F: Fn(A) -> R + Send + Sync + 'static,
    {
        self.exsequi(k)
    }

    /// Creates a continuation that immediately returns the given value.
    ///
    /// This is `return`/`pure` for the continuation monad.
    ///
    /// # Arguments
    ///
    /// * `a` - The value to return
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ordofp_core::transformers::ContinuatioT;
    ///
    /// let cont = ContinuatioT::<i32, i32>::pure(42);
    /// let result = cont.run(|x| x * 2);
    /// assert_eq!(result, 84);
    /// ```
    #[inline]
    pub fn pure(a: A) -> Self
    where
        A: Clone + Send + Sync + 'static,
    {
        ContinuatioT::new(move |k| k(a.clone()))
    }

    /// Maps a function over the value inside this continuation.
    ///
    /// # Arguments
    ///
    /// * `f` - A function that transforms `A` into `B`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ordofp_core::transformers::ContinuatioT;
    ///
    /// let cont = ContinuatioT::<i32, i32>::pure(42);
    /// let doubled = cont.map(|x| x * 2);
    /// assert_eq!(doubled.run(|x| x), 84);
    /// ```
    #[inline]
    pub fn map<B, F>(self, f: F) -> ContinuatioT<R, B>
    where
        F: Fn(A) -> B + Send + Sync + 'static,
        B: 'static,
    {
        let f = Arc::new(f);
        let run_cont = self.run_cont;
        ContinuatioT::new(move |k| {
            let f = f.clone();
            run_cont(Arc::new(move |a| k(f(a))))
        })
    }

    /// Monadic bind operation for the continuation monad.
    ///
    /// Sequences continuation computations.
    ///
    /// # Arguments
    ///
    /// * `f` - A function that transforms `A` into a new continuation
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ordofp_core::transformers::ContinuatioT;
    ///
    /// let cont = ContinuatioT::<i32, i32>::pure(5);
    /// let doubled = cont.bind(|x| ContinuatioT::pure(x * 2));
    /// assert_eq!(doubled.run(|x| x), 10);
    /// ```
    #[inline]
    pub fn bind<B, F>(self, f: F) -> ContinuatioT<R, B>
    where
        F: Fn(A) -> ContinuatioT<R, B> + Send + Sync + 'static,
        B: 'static,
    {
        let f = Arc::new(f);
        let run_cont = self.run_cont;
        ContinuatioT::new(move |k| {
            let f = f.clone();
            let k = k.clone();
            run_cont(Arc::new(move |a| {
                let cont_b = f(a);
                (cont_b.run_cont)(k.clone())
            }))
        })
    }

    /// Alias for `bind`.
    #[inline]
    pub fn flat_map<B, F>(self, f: F) -> ContinuatioT<R, B>
    where
        F: Fn(A) -> ContinuatioT<R, B> + Send + Sync + 'static,
        B: 'static,
    {
        self.bind(f)
    }

    /// Call with current continuation (call/cc).
    ///
    /// Captures the current continuation and passes it to the given function.
    /// This enables advanced control flow patterns like early returns.
    ///
    /// # Arguments
    ///
    /// * `f` - A function that receives an escape continuation
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use ordofp_core::transformers::ContinuatioT;
    ///
    /// // Use call_cc to implement early return
    /// let computation = ContinuatioT::<i32, i32>::call_cc(|exit| {
    ///     // If condition is met, exit early
    ///     if 5 > 3 {
    ///         exit(10)
    ///     } else {
    ///         ContinuatioT::pure(5)
    ///     }
    /// });
    ///
    /// assert_eq!(computation.run(|x| x), 10);
    /// ```
    #[inline]
    pub fn call_cc<B, F>(f: F) -> ContinuatioT<R, A>
    where
        F: Fn(Arc<dyn Fn(A) -> ContinuatioT<R, B> + Send + Sync>) -> ContinuatioT<R, A>
            + Send
            + Sync
            + 'static,
        A: Clone + Send + Sync + 'static,
        B: 'static,
    {
        ContinuatioT::new(move |k| {
            let k_clone = k.clone();
            let escape = Arc::new(move |a: A| {
                let k_inner = k_clone.clone();
                ContinuatioT::<R, B>::new(move |_ignored| k_inner(a.clone()))
            });
            (f(escape).run_cont)(k)
        })
    }
}

/// Applies a function wrapped in a continuation to a value in another continuation.
impl<R: 'static, A: 'static> ContinuatioT<R, A> {
    /// Applicative apply operation.
    ///
    /// # Arguments
    ///
    /// * `cf` - A continuation containing a function
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use ordofp_core::transformers::ContinuatioT;
    ///
    /// let cont_val = ContinuatioT::<i32, i32>::pure(5);
    /// let cont_fn: ContinuatioT<i32, Arc<dyn Fn(i32) -> i32 + Send + Sync>> =
    ///     ContinuatioT::pure(Arc::new(|x| x * 2) as Arc<dyn Fn(i32) -> i32 + Send + Sync>);
    ///
    /// let result = cont_val.apply(cont_fn).run(|x| x);
    /// assert_eq!(result, 10);
    /// ```
    #[inline]
    pub fn apply<B>(
        self,
        cf: ContinuatioT<R, Arc<dyn Fn(A) -> B + Send + Sync>>,
    ) -> ContinuatioT<R, B>
    where
        B: 'static,
    {
        let run_val = self.run_cont;
        let run_fn = cf.run_cont;
        ContinuatioT::new(move |k| {
            let run_val = run_val.clone();
            let k = Arc::new(k);
            run_fn(Arc::new(move |f| {
                let k = k.clone();
                run_val(Arc::new(move |a| k(f(a))))
            }))
        })
    }
}

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

    #[test]
    fn test_pure_and_run() {
        let cont = ContinuatioT::<i32, i32>::pure(42);
        assert_eq!(cont.run(|x| x), 42);
        assert_eq!(cont.run(|x| x * 2), 84);
    }

    #[test]
    fn test_map() {
        let cont = ContinuatioT::<i32, i32>::pure(21);
        let doubled = cont.map(|x| x * 2);
        assert_eq!(doubled.run(|x| x), 42);
    }

    #[test]
    fn test_bind_chain() {
        let result = ContinuatioT::<i32, i32>::pure(5)
            .bind(|x| ContinuatioT::pure(x + 3))
            .bind(|x| ContinuatioT::pure(x * 2))
            .run(|x| x);

        assert_eq!(result, 16); // (5 + 3) * 2
    }

    #[test]
    fn test_call_cc_early_exit() {
        let result = ContinuatioT::<i32, i32>::call_cc(|exit| {
            if 10 > 5 {
                exit(100)
            } else {
                ContinuatioT::pure(0)
            }
        })
        .run(|x| x);

        assert_eq!(result, 100);
    }

    #[test]
    fn test_call_cc_no_exit() {
        let result = ContinuatioT::<i32, i32>::call_cc(
            |_exit: Arc<dyn Fn(i32) -> ContinuatioT<i32, i32> + Send + Sync>| {
                ContinuatioT::pure(42)
            },
        )
        .run(|x| x);

        assert_eq!(result, 42);
    }

    #[test]
    fn test_left_identity() {
        // pure(a).bind(f) == f(a)
        let a = 5;
        let f = |x: i32| ContinuatioT::pure(x * 2);

        let left = ContinuatioT::<i32, i32>::pure(a).bind(f);
        let right = f(a);

        assert_eq!(left.run(|x| x), right.run(|x| x));
    }

    #[test]
    fn test_right_identity() {
        // m.bind(pure) == m
        let m = ContinuatioT::<i32, i32>::pure(42);
        let bound = m.clone().bind(ContinuatioT::pure);

        assert_eq!(m.run(|x| x), bound.run(|x| x));
    }

    #[test]
    fn test_associativity() {
        // (m.bind(f)).bind(g) == m.bind(|x| f(x).bind(g))
        let m = ContinuatioT::<i32, i32>::pure(5);

        let left = m
            .clone()
            .bind(|x| ContinuatioT::pure(x + 1))
            .bind(|x| ContinuatioT::pure(x * 2));

        let right = m.bind(|x| {
            let inner = ContinuatioT::pure(x + 1);
            inner.bind(|y| ContinuatioT::pure(y * 2))
        });

        assert_eq!(left.run(|x| x), right.run(|x| x));
    }
}