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
// Copyright (C) 2026 Industrial Algebra
// SPDX-License-Identifier: Apache-2.0
#[cfg(feature = "std")]
use std::boxed::Box;
#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::boxed::Box;
use core::marker::PhantomData;
use karpal_core::applicative::Applicative;
use karpal_core::hkt::HKT;
// ---- Private dyn-safe trait for existential encoding ----
/// Dyn-safe trait for a node in the Free Applicative tree.
///
/// Each node erases some intermediate type `B` via trait-object dispatch.
/// Only methods that use types already in the trait parameters (F, A) are
/// dyn-compatible.
trait FreeApNode<F: HKT + 'static, A: 'static> {
/// Retract into F's own Applicative. Dyn-safe because F and A are
/// trait-level type parameters.
fn retract_node(self: Box<Self>) -> F::Of<A>
where
F: Applicative;
/// Count the number of `lift_f` effects in this subtree.
fn count_effects(&self) -> usize;
}
/// Lift node: stores `F<B>` and continuation `FreeAp<F, Box<dyn Fn(B) -> A>>`.
///
/// Represents the GADT constructor: `Ap :: f b -> FreeAp f (b -> a) -> FreeAp f a`
struct LiftNode<F: HKT + 'static, A: 'static, B: Clone + 'static> {
effect: F::Of<B>,
rest: FreeAp<F, Box<dyn Fn(B) -> A>>,
}
impl<F: HKT + 'static, A: 'static, B: Clone + 'static> FreeApNode<F, A> for LiftNode<F, A, B> {
fn retract_node(self: Box<Self>) -> F::Of<A>
where
F: Applicative,
{
let f_fn: F::Of<Box<dyn Fn(B) -> A>> = self.rest.retract();
let f_b: F::Of<B> = self.effect;
F::ap(f_fn, f_b)
}
fn count_effects(&self) -> usize {
1 + self.rest.count_effects()
}
}
/// Fmap node: deferred map operation.
struct FmapNode<F: HKT + 'static, Src: 'static, A: 'static> {
inner: FreeAp<F, Src>,
transform: Box<dyn Fn(Src) -> A>,
}
impl<F: HKT + 'static, Src: 'static, A: 'static> FreeApNode<F, A> for FmapNode<F, Src, A> {
fn retract_node(self: Box<Self>) -> F::Of<A>
where
F: Applicative,
{
let f_src: F::Of<Src> = self.inner.retract();
F::fmap(f_src, self.transform)
}
fn count_effects(&self) -> usize {
self.inner.count_effects()
}
}
/// Ap node: deferred applicative application.
struct ApNode<F: HKT + 'static, Src: Clone + 'static, A: 'static> {
ff: FreeAp<F, Box<dyn Fn(Src) -> A>>,
fa: FreeAp<F, Src>,
}
impl<F: HKT + 'static, Src: Clone + 'static, A: 'static> FreeApNode<F, A> for ApNode<F, Src, A> {
fn retract_node(self: Box<Self>) -> F::Of<A>
where
F: Applicative,
{
let f_fn: F::Of<Box<dyn Fn(Src) -> A>> = self.ff.retract();
let f_src: F::Of<Src> = self.fa.retract();
F::ap(f_fn, f_src)
}
fn count_effects(&self) -> usize {
self.ff.count_effects() + self.fa.count_effects()
}
}
// ---- Public FreeAp type ----
#[allow(private_interfaces)]
/// Free Applicative Functor — build applicative computations as data.
///
/// `FreeAp<F, A>` stores a computation tree where effects from `F`
/// can be statically analyzed before interpretation. Unlike `Free<F, A>`
/// (the free monad), effects in `FreeAp` do not depend on the results
/// of previous effects.
///
/// ```text
/// Pure(a) — a finished computation
/// Ap(node) — an effect step (existentially quantified)
/// ```
///
/// # Interpretation
///
/// The primary eliminator is `retract`, which collapses the tree into
/// `F`'s own applicative. To interpret into a *different* applicative `M`
/// via a natural transformation `NT: F ~> M`, apply `NT` at each
/// `lift_f` call site:
///
/// ```text
/// // Instead of fold_map:
/// let free_m: FreeAp<M, A> = build_tree_with(|effect| lift_f(NT::transform(effect)));
/// let result: M::Of<A> = free_m.retract();
/// ```
///
/// This decomposition (`fold_map nt ≡ retract . hoist nt`) is necessary
/// because Rust's type system cannot dispatch a generic natural
/// transformation through trait objects (the intermediate type `B` is
/// erased, preventing compile-time monomorphization of `NT::transform<B>`).
///
/// # When to use FreeAp vs Free
///
/// - Use `FreeAp<F, A>` when effects are independent and you want
/// static analysis of the effect structure.
/// - Use `Free<F, A>` when later effects depend on earlier results
/// (monadic sequencing).
pub enum FreeAp<F: HKT + 'static, A: 'static> {
/// A pure value.
Pure(A),
/// An effect step with erased intermediate type.
Ap(Box<dyn FreeApNode<F, A>>),
}
impl<F: HKT + 'static, A: 'static> FreeAp<F, A> {
/// Wrap a pure value into the free applicative.
pub fn pure(a: A) -> Self {
FreeAp::Pure(a)
}
/// Lift a single effect `F<A>` into the free applicative.
///
/// `A: Clone` is required because `Apply::ap` needs it.
pub fn lift_f(fa: F::Of<A>) -> Self
where
A: Clone,
F::Of<A>: 'static,
{
FreeAp::Ap(Box::new(LiftNode {
effect: fa,
rest: FreeAp::Pure(Box::new(|b| b) as Box<dyn Fn(A) -> A>),
}))
}
/// Map a function over the result. No bounds on `F` required.
pub fn fmap<B: 'static>(self, f: impl Fn(A) -> B + 'static) -> FreeAp<F, B> {
match self {
FreeAp::Pure(a) => FreeAp::Pure(f(a)),
FreeAp::Ap(node) => FreeAp::Ap(Box::new(FmapNode {
inner: FreeAp::Ap(node),
transform: Box::new(f),
})),
}
}
/// Applicative `ap`: apply a wrapped function to this value.
///
/// `ff` contains functions `A → B`, `self` contains `A` values.
pub fn ap<B: 'static>(ff: FreeAp<F, Box<dyn Fn(A) -> B>>, fa: FreeAp<F, A>) -> FreeAp<F, B>
where
A: Clone,
{
match ff {
FreeAp::Pure(f) => fa.fmap(f),
FreeAp::Ap(node) => FreeAp::Ap(Box::new(ApNode {
ff: FreeAp::Ap(node),
fa,
})),
}
}
/// Interpret by collapsing back into `F` itself.
///
/// Requires `F: Applicative`.
pub fn retract(self) -> F::Of<A>
where
F: Applicative,
{
match self {
FreeAp::Pure(a) => F::pure(a),
FreeAp::Ap(node) => node.retract_node(),
}
}
/// Count the number of `lift_f` effects in this computation tree.
///
/// This demonstrates the key advantage of free applicatives over
/// free monads: the tree structure can be statically analyzed
/// without interpretation.
pub fn count_effects(&self) -> usize {
match self {
FreeAp::Pure(_) => 0,
FreeAp::Ap(node) => node.count_effects(),
}
}
}
/// Marker type for `FreeAp<F, _>`.
///
/// Note: Cannot implement `HKT` or `Functor` due to Rust's GAT limitations
/// (`type Of<T>` cannot add `T: 'static` in impl when trait doesn't have it).
/// Use `FreeAp::fmap` directly.
pub struct FreeApF<F: HKT + 'static>(PhantomData<F>);
#[cfg(test)]
mod tests {
use super::*;
use karpal_core::hkt::OptionF;
#[test]
fn pure_retract() {
let fa = FreeAp::<OptionF, i32>::pure(42);
let result = fa.retract();
assert_eq!(result, Some(42));
}
#[test]
fn lift_f_retract() {
let fa = FreeAp::<OptionF, i32>::lift_f(Some(10));
let result = fa.retract();
assert_eq!(result, Some(10));
}
#[test]
fn lift_f_none() {
let fa = FreeAp::<OptionF, i32>::lift_f(None);
let result = fa.retract();
assert_eq!(result, None);
}
#[test]
fn fmap_pure_retract() {
let fa = FreeAp::<OptionF, i32>::pure(5).fmap(|x| x * 3);
let result = fa.retract();
assert_eq!(result, Some(15));
}
#[test]
fn fmap_lift_retract() {
let fa = FreeAp::<OptionF, i32>::lift_f(Some(4)).fmap(|x| x + 10);
let result = fa.retract();
assert_eq!(result, Some(14));
}
#[test]
fn ap_pure_pure() {
let ff = FreeAp::<OptionF, Box<dyn Fn(i32) -> i32>>::pure(
Box::new(|x| x * 2) as Box<dyn Fn(i32) -> i32>
);
let fa = FreeAp::<OptionF, i32>::pure(21);
let result = FreeAp::ap(ff, fa).retract();
assert_eq!(result, Some(42));
}
#[test]
fn ap_lift_lift() {
let ff = FreeAp::<OptionF, Box<dyn Fn(i32) -> i32>>::pure(
Box::new(|x| x + 100) as Box<dyn Fn(i32) -> i32>
);
let fa = FreeAp::<OptionF, i32>::lift_f(Some(5));
let result = FreeAp::ap(ff, fa).retract();
assert_eq!(result, Some(105));
}
#[test]
fn count_effects_pure() {
let fa = FreeAp::<OptionF, i32>::pure(42);
assert_eq!(fa.count_effects(), 0);
}
#[test]
fn count_effects_single() {
let fa = FreeAp::<OptionF, i32>::lift_f(Some(1));
assert_eq!(fa.count_effects(), 1);
}
#[test]
fn count_effects_fmapped() {
let fa = FreeAp::<OptionF, i32>::lift_f(Some(1)).fmap(|x| x + 1);
assert_eq!(fa.count_effects(), 1);
}
#[test]
fn count_effects_ap() {
let ff =
FreeAp::<OptionF, Box<dyn Fn(i32) -> String>>::pure(
Box::new(|x: i32| format!("{x}")) as Box<dyn Fn(i32) -> String>
);
let fa = FreeAp::<OptionF, i32>::lift_f(Some(5));
let apped = FreeAp::ap(ff, fa);
// pure contributes 0, lift_f contributes 1
assert_eq!(apped.count_effects(), 1);
}
#[test]
fn fmap_identity() {
let fa = FreeAp::<OptionF, i32>::lift_f(Some(7));
let mapped = fa.fmap(|x| x);
let result = mapped.retract();
assert_eq!(result, Some(7));
}
#[test]
fn fmap_composition() {
let f = |x: i32| x + 1;
let g = |x: i32| x * 2;
let left = FreeAp::<OptionF, i32>::lift_f(Some(3))
.fmap(move |a| g(f(a)))
.retract();
let right = FreeAp::<OptionF, i32>::lift_f(Some(3))
.fmap(f)
.fmap(g)
.retract();
assert_eq!(left, right);
}
#[test]
fn multiple_fmaps() {
let fa = FreeAp::<OptionF, i32>::lift_f(Some(2))
.fmap(|x| x * 10)
.fmap(|x| x + 5);
let result = fa.retract();
assert_eq!(result, Some(25)); // 2*10+5
}
}
#[cfg(test)]
mod law_tests {
use super::*;
use karpal_core::hkt::OptionF;
use proptest::prelude::*;
proptest! {
// Functor identity: fmap(id)(x) == x
#[test]
fn functor_identity(a in any::<i32>()) {
let original = FreeAp::<OptionF, i32>::lift_f(Some(a)).retract();
let mapped = FreeAp::<OptionF, i32>::lift_f(Some(a)).fmap(|x| x).retract();
prop_assert_eq!(original, mapped);
}
// Functor composition: fmap(g . f) == fmap(f) . fmap(g)
#[test]
fn functor_composition(a in any::<i32>()) {
let f = |x: i32| x.wrapping_add(1);
let g = |x: i32| x.wrapping_mul(2);
let left = FreeAp::<OptionF, i32>::lift_f(Some(a))
.fmap(move |x| g(f(x)))
.retract();
let right = FreeAp::<OptionF, i32>::lift_f(Some(a))
.fmap(f)
.fmap(g)
.retract();
prop_assert_eq!(left, right);
}
// Applicative identity: ap(pure(id), x) == x
#[test]
fn applicative_identity(a in any::<i32>()) {
let id_fn = FreeAp::<OptionF, Box<dyn Fn(i32) -> i32>>::pure(
Box::new(|x| x) as Box<dyn Fn(i32) -> i32>,
);
let fa = FreeAp::<OptionF, i32>::lift_f(Some(a));
let result = FreeAp::ap(id_fn, fa).retract();
let expected = FreeAp::<OptionF, i32>::lift_f(Some(a)).retract();
prop_assert_eq!(result, expected);
}
// Applicative homomorphism: ap(pure(f), pure(x)) == pure(f(x))
#[test]
fn applicative_homomorphism(a in any::<i32>()) {
let ff = FreeAp::<OptionF, Box<dyn Fn(i32) -> i32>>::pure(
Box::new(|x: i32| x.wrapping_mul(3)) as Box<dyn Fn(i32) -> i32>,
);
let fa = FreeAp::<OptionF, i32>::pure(a);
let left = FreeAp::ap(ff, fa).retract();
let right = FreeAp::<OptionF, i32>::pure(a.wrapping_mul(3)).retract();
prop_assert_eq!(left, right);
}
}
}