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
pub mod hkt {
//! # Higher-Kinded Type (HKT) Monad and Bind
//!
//! This module defines the `Monad` and `Bind` traits for HKTs.
//!
//! - [`Bind`]: Provides the `bind` method (often called `flatMap` or `>>=`),
//! which allows sequencing operations that return a monadic value. It extends [`Apply`].
//! - [`Monad`]: Extends [`Applicative`] (and thus `Bind` via `Applicative`'s supertrait `Apply`)
//! and adds the `join` method, which flattens a nested monadic structure (e.g., `F<F<A>>` to `F<A>`).
//! Alternatively, a monad can be defined by `pure` (from `Applicative`) and `bind`.
//!
//! ## Example
//!
//! ```
//! use monadify::monad::hkt::{Monad, Bind};
//! use monadify::applicative::hkt::Applicative; // For pure
//! use monadify::kind_based::kind::OptionHKTMarker;
//!
//! // Using bind
//! let opt_val: Option<i32> = Some(5);
//! let bind_fn = |x: i32| if x > 0 { Some(x * 2) } else { None };
//! let result_bind: Option<i32> = OptionHKTMarker::bind(opt_val, bind_fn);
//! assert_eq!(result_bind, Some(10));
//!
//! let opt_val_none: Option<i32> = Some(-5);
//! let result_bind_none: Option<i32> = OptionHKTMarker::bind(opt_val_none, bind_fn);
//! assert_eq!(result_bind_none, None);
//!
//! // Using join
//! let nested_opt: Option<Option<String>> = Some(Some("hello".to_string()));
//! let joined_opt: Option<String> = OptionHKTMarker::join(nested_opt);
//! assert_eq!(joined_opt, Some("hello".to_string()));
//!
//! let nested_none_inner: Option<Option<String>> = Some(None);
//! let joined_none_inner: Option<String> = OptionHKTMarker::join(nested_none_inner);
//! assert_eq!(joined_none_inner, None);
//!
//! let nested_none_outer: Option<Option<String>> = None;
//! let joined_none_outer: Option<String> = OptionHKTMarker::join(nested_none_outer);
//! assert_eq!(joined_none_outer, None);
//! ```
use crate::applicative::hkt::Applicative; // HKT Applicative
use crate::apply::hkt::Apply; // HKT Apply
use crate::function::{CFn, CFnOnce};
use crate::kind_based::kind::{
HKT, HKT1, OptionHKTMarker, ResultHKTMarker, VecHKTMarker, CFnHKTMarker, CFnOnceHKTMarker
};
/// HKT-based `Monad` trait.
///
/// A `Monad` allows for sequencing computations within a context. It extends
/// [`Applicative`]. The key additional operation is `join`, which flattens
/// nested monadic structures.
///
/// `Self` refers to the HKT marker type (e.g., [`OptionHKTMarker`]) that implements
/// [`HKT1`] and [`Applicative`].
/// `A` is the type of the value held within the monadic context (e.g., the `T` in `Option<T>`).
///
/// ## Monad Laws
/// Implementors must satisfy several laws:
/// 1. **Left Identity**: `bind(pure(x), f) == f(x)`
/// 2. **Right Identity**: `bind(m, pure) == m`
/// 3. **Associativity**: `bind(bind(m, f), g) == bind(m, |x| bind(f(x), g))`
///
/// These laws can also be expressed using `join`, `pure`, and `map` (from `Functor`,
/// which `Applicative` extends):
/// 1. `join(pure(m)) == m`
/// 2. `join(map(m, pure)) == m`
/// 3. `join(map(mma, join)) == join(join(mma))` (if `map` is defined for `F<F<F<A>>>`)
/// or more commonly: `join(map(mmma, |mma| join(mma))) == join(join(mmma))`
pub trait Monad<A>: Applicative<A> // Monad holds type A
where
Self: Sized + HKT1, // Self is the HKT Marker
A: 'static,
{
/// Flattens a nested monadic structure.
///
/// For an HKT `F`, `join` takes `F<F<A>>` and returns `F<A>`.
///
/// # Example
/// ```
/// use monadify::monad::hkt::Monad;
/// use monadify::kind_based::kind::OptionHKTMarker;
///
/// let nested: Option<Option<i32>> = Some(Some(10));
/// let flat: Option<i32> = OptionHKTMarker::join(nested);
/// assert_eq!(flat, Some(10));
///
/// let nested_none: Option<Option<i32>> = Some(None);
/// assert_eq!(OptionHKTMarker::join(nested_none), None);
/// ```
fn join(mma: Self::Applied<Self::Applied<A>>) -> Self::Applied<A>;
}
/// HKT-based `Bind` trait (equivalent to `flatMap` or Haskell's `>>=`).
///
/// `Bind` allows sequencing operations where each operation takes a normal value
/// and returns a value wrapped in the HKT context. It extends [`Apply`].
///
/// `Self` refers to the HKT marker type (e.g., [`OptionHKTMarker`]).
/// `A` is the type of the value within the input HKT context `Self::Applied<A>`.
/// `B` is the type of the value within the output HKT context `Self::Applied<B>`
/// that the provided function `func` returns.
///
/// ## Example
/// ```
/// use monadify::monad::hkt::Bind;
/// use monadify::kind_based::kind::OptionHKTMarker;
///
/// let opt_val: Option<i32> = Some(5);
///
/// // Function that returns an Option
/// let half = |x: i32| -> Option<f64> {
/// if x % 2 == 0 { Some((x as f64) / 2.0) } else { None }
/// };
///
/// let result: Option<f64> = OptionHKTMarker::bind(opt_val, half); // Fails as 5 is odd
/// assert_eq!(result, None);
///
/// let result_even: Option<f64> = OptionHKTMarker::bind(Some(10), half); // Succeeds
/// assert_eq!(result_even, Some(5.0));
/// ```
pub trait Bind<A, B>: Apply<A, B>
where
Self: Sized + HKT1,
A: 'static,
B: 'static,
// Self::Applied<B>: 'static, // This was for the default impl, may not be needed at trait level.
// Apply<A,B> already requires B: 'static.
{
/// Sequentially composes computations within the HKT context.
///
/// Takes a value in context (`Self::Applied<A>`) and a function (`A -> Self::Applied<B>`).
/// It applies the function to the unwrapped value (if present/valid) and returns
/// the resulting context `Self::Applied<B>`.
fn bind(input: Self::Applied<A>, func: impl FnMut(A) -> Self::Applied<B> + Clone + 'static) -> Self::Applied<B>;
}
// --- Bind Implementations ---
impl<A: 'static, B: 'static> Bind<A, B> for OptionHKTMarker {
/// For `Option`, `bind` is equivalent to `Option::and_then`.
/// If `input` is `Some(a)`, it applies `func` to `a`.
/// If `input` is `None`, it returns `None`.
fn bind(input: Self::Applied<A>, func: impl FnMut(A) -> Self::Applied<B> + Clone + 'static) -> Self::Applied<B> {
input.and_then(func)
}
}
impl<A: 'static, B: 'static, E: 'static + Clone> Bind<A, B> for ResultHKTMarker<E> {
/// For `Result`, `bind` is equivalent to `Result::and_then`.
/// If `input` is `Ok(a)`, it applies `func` to `a`.
/// If `input` is `Err(e)`, it propagates the `Err(e)`.
fn bind(input: Self::Applied<A>, func: impl FnMut(A) -> Self::Applied<B> + Clone + 'static) -> Self::Applied<B> {
input.and_then(func)
}
}
impl<A: 'static + Clone, B: 'static> Bind<A, B> for VecHKTMarker {
/// For `Vec`, `bind` applies `func` to each element and flattens the results.
/// This is equivalent to `Vec::into_iter().flat_map(func).collect()`.
fn bind(input: Self::Applied<A>, func: impl FnMut(A) -> Self::Applied<B> + Clone + 'static) -> Self::Applied<B> {
input.into_iter().flat_map(func).collect()
}
}
// Bind for CFnHKTMarker<R> (Kleisli composition for R -> _)
// input: Self::Applied<A> which is CFn<R, A>
// func: A -> Self::Applied<B> which is A -> CFn<R, B> (a function producing a function)
// result: Self::Applied<B> which is CFn<R, B> (a new function R -> B)
impl<R, A, B: 'static> Bind<A, B> for CFnHKTMarker<R>
where
R: 'static + Clone, // Clone for `r.clone()`
A: 'static,
// Bind trait now only requires Apply<A,B> as a supertrait.
Self: Apply<A,B>,
Self: HKT<Applied<A> = CFn<R, A>>,
Self: HKT<Applied<B> = CFn<R, B>>,
{
/// Implements Kleisli composition for functions `R -> A` and `A -> (R -> B)`.
///
/// Given `input_fn: R -> A` and `func: A -> (R -> B)`,
/// produces a new function `R -> B`.
/// The new function, when called with `r: R`:
/// 1. Calls `input_fn(r)` to get `a: A`.
/// 2. Calls `func(a)` to get `output_fn: R -> B`.
/// 3. Calls `output_fn(r)` to get `b: B`.
fn bind(input: Self::Applied<A>, func: impl FnMut(A) -> Self::Applied<B> + Clone + 'static) -> Self::Applied<B> {
let concrete_input_fn = input;
CFn::new(move |r: R| {
let a_val = concrete_input_fn.call(r.clone());
let mut func_clone = func.clone(); // Clone for this call, as CFn::new needs Fn
let cfn_r_b = func_clone(a_val); // cfn_r_b is CFn<R, B>
cfn_r_b.call(r.clone())
})
}
}
impl<R, A, B: 'static> Bind<A, B> for CFnOnceHKTMarker<R>
where
R: 'static + Clone,
A: 'static,
// Bind trait now only requires Apply<A,B> as a supertrait.
Self: Apply<A,B>,
Self: HKT<Applied<A> = CFnOnce<R, A>>,
Self: HKT<Applied<B> = CFnOnce<R, B>>,
{
/// Implements Kleisli composition for functions `R -> A` (once) and `A -> (R -> B)` (once).
///
/// Similar to `CFnHKTMarker::bind`, but for `CFnOnce`.
/// The resulting function `R -> B` can also only be called once.
fn bind(input: Self::Applied<A>, mut func: impl FnMut(A) -> Self::Applied<B> + Clone + 'static) -> Self::Applied<B> {
let concrete_input = input; // CFnOnce<R,A>
CFnOnce::new(move |r: R| {
let a_val = concrete_input.call_once(r.clone());
let cfn_once_r_b = func(a_val); // CFnOnce<R,B>
cfn_once_r_b.call_once(r)
})
}
}
// --- Monad Implementations ---
impl<A: 'static> Monad<A> for OptionHKTMarker {
/// Flattens `Option<Option<A>>` to `Option<A>`.
/// `Some(Some(a))` becomes `Some(a)`.
/// `Some(None)` becomes `None`.
/// `None` becomes `None`.
fn join(mma: Self::Applied<Self::Applied<A>>) -> Self::Applied<A> { // mma is Option<Option<A>>
mma.and_then(core::convert::identity)
}
}
impl<A: 'static, E: 'static + Clone> Monad<A> for ResultHKTMarker<E> {
/// Flattens `Result<Result<A, E>, E>` to `Result<A, E>`.
/// `Ok(Ok(a))` becomes `Ok(a)`.
/// `Ok(Err(e))` becomes `Err(e)`.
/// `Err(e)` becomes `Err(e)`.
fn join(mma: Self::Applied<Self::Applied<A>>) -> Self::Applied<A> { // mma is Result<Result<A,E>, E>
mma.and_then(core::convert::identity)
}
}
impl<A: 'static + Clone> Monad<A> for VecHKTMarker {
/// Flattens `Vec<Vec<A>>` to `Vec<A>`.
/// `vec![vec![1, 2], vec![3]]` becomes `vec![1, 2, 3]`.
fn join(mma: Self::Applied<Self::Applied<A>>) -> Self::Applied<A> { // mma is Vec<Vec<A>>
mma.into_iter().flatten().collect()
}
}
impl<R, A> Monad<A> for CFnHKTMarker<R>
where
R: 'static + Clone,
A: 'static + Clone, // From Applicative supertrait for CFnHKTMarker<R>
{
/// Flattens `CFn<R, CFn<R, A>>` to `CFn<R, A>`.
///
/// This is achieved by using `bind` with the identity function `|ma: CFn<R,A>| ma`.
/// Given `mma: R -> (R -> A)`, produces `R -> A`.
/// The new function, when called with `r: R`:
/// 1. Calls `mma(r)` to get `ma: R -> A`.
/// 2. Calls `ma(r)` to get `a: A`.
fn join(mma: Self::Applied<Self::Applied<A>>) -> Self::Applied<A> { // mma is CFn<R, CFn<R,A>>
// Bind<Self::Applied<A>, A> means Bind<CFn<R,A>, A>
<Self as Bind<Self::Applied<A>, A>>::bind(mma, |ma: Self::Applied<A>| ma)
}
}
impl<R, A> Monad<A> for CFnOnceHKTMarker<R>
where
R: 'static + Clone,
A: 'static + Clone, // From Applicative supertrait for CFnOnceHKTMarker<R>
{
/// Flattens `CFnOnce<R, CFnOnce<R, A>>` to `CFnOnce<R, A>`.
///
/// Similar to `CFnHKTMarker::join`, but for `CFnOnce`.
fn join(mma: Self::Applied<Self::Applied<A>>) -> Self::Applied<A> { // mma is CFnOnce<R, CFnOnce<R,A>>
<Self as Bind<Self::Applied<A>, A>>::bind(mma, |ma: Self::Applied<A>| ma)
}
}
/// Helper function for `Bind::bind`.
///
/// This allows calling `bind(func, ma)` instead of `F::bind(ma, func)`.
///
/// # Example
/// ```
/// use monadify::monad::hkt::bind; // The helper function
/// use monadify::kind_based::kind::OptionHKTMarker;
///
/// let opt_val: Option<i32> = Some(5);
/// let half = |x: i32| if x % 2 == 0 { Some((x as f64) / 2.0) } else { None };
///
/// // Note: Type of F (OptionHKTMarker) might need to be inferred or specified
/// let result: Option<f64> = bind::<OptionHKTMarker, _, _, _>(half, opt_val);
/// assert_eq!(result, None);
/// ```
pub fn bind<F, A, B, FuncImpl>(
func: FuncImpl,
ma: F::Applied<A>,
) -> F::Applied<B>
where
F: Bind<A, B> + HKT1, // F is the HKTMarker
FuncImpl: FnMut(A) -> F::Applied<B> + Clone + 'static, // Added Clone + 'static
A: 'static,
B: 'static, // B needs to be 'static for F::Applied<B>
{
F::bind(ma, func)
}
}
// Directly export HKT Bind, Monad, and helper bind
pub use hkt::{Bind, Monad, bind};
// Note: join is a method on the Monad trait in the hkt module.