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
//! By-ref monads, combining [`RefApplicative`](crate::classes::RefApplicative) and [`RefSemimonad`](crate::classes::RefSemimonad).
//!
//! This is the by-ref counterpart of [`Monad`](crate::classes::Monad).
//! Enables monadic sequencing where the continuation receives `&A` instead
//! of owned `A`, and value injection clones from `&A`.
//!
//! ### Examples
//!
//! ```
//! use fp_library::{
//! brands::*,
//! classes::*,
//! functions::{
//! explicit::bind,
//! *,
//! },
//! types::*,
//! };
//!
//! // Chain computations on memoized values by reference
//! let lazy = ref_pure::<LazyBrand<RcLazyConfig>, _>(&5);
//! let result = bind::<LazyBrand<RcLazyConfig>, _, _, _, _>(&lazy, |x: &i32| {
//! let v = *x * 2;
//! ref_pure::<LazyBrand<RcLazyConfig>, _>(&v)
//! });
//! assert_eq!(*result.evaluate(), 10);
//! ```
#[fp_macros::document_module]
mod inner {
use {
crate::{
classes::*,
kinds::*,
},
fp_macros::*,
};
/// A type class for by-ref monads.
///
/// Combines [`RefApplicative`] (by-ref pure + apply) with
/// [`RefSemimonad`] (by-ref bind).
///
/// This is the by-ref counterpart of [`Monad`]. Automatically
/// implemented for any type implementing both supertraits.
///
/// A lawful `RefMonad` must satisfy three laws:
///
/// 1. **Left identity**: `bind(ref_pure(&a), f)` evaluates to the
/// same value as `f(&a)`.
/// 2. **Right identity**: `bind(m, |x| ref_pure(x))` evaluates to
/// the same value as `m`.
/// 3. **Associativity**: `bind(bind(m, f), g)` evaluates to the
/// same value as `bind(m, |x| bind(f(x), g))`.
///
/// These are the standard monad laws expressed with by-ref operations.
/// Equality is by evaluated value, not structural identity, since
/// memoized types like [`Lazy`](crate::types::Lazy) create new
/// allocations on each construction.
#[document_examples]
///
/// ```
/// use fp_library::{
/// brands::*,
/// classes::*,
/// functions::{
/// explicit::bind,
/// *,
/// },
/// types::*,
/// };
///
/// let f = |x: &i32| {
/// let v = *x + 1;
/// Lazy::<_, RcLazyConfig>::new(move || v)
/// };
/// let g = |x: &i32| {
/// let v = *x * 2;
/// Lazy::<_, RcLazyConfig>::new(move || v)
/// };
///
/// // Left identity: bind(ref_pure(&a), f) = f(&a)
/// let left =
/// bind::<LazyBrand<RcLazyConfig>, _, _, _, _>(&ref_pure::<LazyBrand<RcLazyConfig>, _>(&5), f);
/// assert_eq!(*left.evaluate(), *f(&5).evaluate());
///
/// // Right identity: bind(m, |x| ref_pure(x)) = m
/// let m = RcLazy::pure(42);
/// let right = bind::<LazyBrand<RcLazyConfig>, _, _, _, _>(&m, |x: &i32| {
/// ref_pure::<LazyBrand<RcLazyConfig>, _>(x)
/// });
/// assert_eq!(*right.evaluate(), *m.evaluate());
///
/// // Associativity: bind(bind(m, f), g) = bind(m, |x| bind(f(x), g))
/// let m = RcLazy::pure(3);
/// let lhs = bind::<LazyBrand<RcLazyConfig>, _, _, _, _>(
/// &bind::<LazyBrand<RcLazyConfig>, _, _, _, _>(&m, f),
/// g,
/// );
/// let rhs = bind::<LazyBrand<RcLazyConfig>, _, _, _, _>(&m, |x: &i32| {
/// bind::<LazyBrand<RcLazyConfig>, _, _, _, _>(&f(x), g)
/// });
/// assert_eq!(*lhs.evaluate(), *rhs.evaluate());
/// ```
pub trait RefMonad: RefApplicative + RefSemimonad {}
/// Blanket implementation of [`RefMonad`].
#[document_type_parameters("The brand type.")]
impl<Brand> RefMonad for Brand where Brand: RefApplicative + RefSemimonad {}
/// Executes a monadic action conditionally, using by-ref bind.
///
/// Evaluates the monadic boolean condition by reference, then returns
/// one of the two branches depending on the result.
#[document_signature]
///
#[document_type_parameters(
"The lifetime of the computations.",
"The brand of the monad.",
"The type of the result."
)]
///
#[document_parameters(
"The monadic boolean condition.",
"The value if true.",
"The value if false."
)]
///
#[document_returns("The selected branch.")]
#[document_examples]
///
/// ```
/// use fp_library::{
/// brands::*,
/// functions::*,
/// types::*,
/// };
///
/// let cond = RcLazy::pure(true);
/// let then_val = RcLazy::pure(1);
/// let else_val = RcLazy::pure(0);
/// let result = ref_if_m::<LazyBrand<RcLazyConfig>, _>(&cond, &then_val, &else_val);
/// assert_eq!(*result.evaluate(), 1);
/// ```
pub fn ref_if_m<'a, Brand: RefMonad, A: 'a>(
cond: &Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, bool>),
then_branch: &Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
else_branch: &Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
) -> Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>)
where
Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>): Clone, {
let then_branch = then_branch.clone();
let else_branch = else_branch.clone();
Brand::ref_bind(
cond,
move |c: &bool| {
if *c { then_branch.clone() } else { else_branch.clone() }
},
)
}
/// Performs a monadic action when a by-ref condition is false.
///
/// Evaluates the monadic boolean condition by reference, then executes
/// the action if the result is `false`, otherwise returns `ref_pure(&())`.
#[document_signature]
///
#[document_type_parameters("The lifetime of the computations.", "The brand of the monad.")]
///
#[document_parameters("The monadic boolean condition.", "The action to execute if false.")]
///
#[document_returns("The action result, or a pure unit value.")]
#[document_examples]
///
/// ```
/// use fp_library::{
/// brands::*,
/// functions::*,
/// types::*,
/// };
///
/// let cond = RcLazy::pure(false);
/// let action = RcLazy::pure(());
/// let result = ref_unless_m::<LazyBrand<RcLazyConfig>>(&cond, &action);
/// assert_eq!(*result.evaluate(), ());
/// ```
pub fn ref_unless_m<'a, Brand: RefMonad>(
cond: &Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, bool>),
action: &Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, ()>),
) -> Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, ()>)
where
Apply!(<Brand as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, ()>): Clone, {
let action = action.clone();
Brand::ref_bind(
cond,
move |c: &bool| {
if *c { Brand::ref_pure(&()) } else { action.clone() }
},
)
}
}
pub use inner::*;