fp-library 0.17.0

A functional programming library for Rust featuring your favourite higher-kinded types and 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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Types that can be mapped over two type arguments simultaneously by reference.
//!
//! ### Examples
//!
//! ```
//! use fp_library::{
//! 	brands::*,
//! 	functions::explicit::*,
//! };
//!
//! let x = Result::<i32, i32>::Ok(5);
//! let y = bimap::<ResultBrand, _, _, _, _, _, _>((|e: &i32| *e + 1, |s: &i32| *s * 2), &x);
//! assert_eq!(y, Ok(10));
//! ```

#[fp_macros::document_module]
mod inner {
	use {
		crate::{
			brands::*,
			classes::*,
			kinds::*,
		},
		fp_macros::*,
	};

	/// A type class for types that can be mapped over two type arguments by reference.
	///
	/// This is the by-reference variant of [`Bifunctor`]. Both closures receive references
	/// to the values (`&A` and `&C`) and produce owned output (`B` and `D`). The container
	/// is borrowed, not consumed.
	///
	/// Unlike [`RefFunctor`] for partially-applied bifunctor brands (e.g.,
	/// `ResultErrAppliedBrand<E>`), `RefBifunctor` does not require `Clone` on either
	/// type parameter because both sides have closures to handle their respective types.
	///
	/// ### Laws
	///
	/// `RefBifunctor` instances must satisfy the following laws:
	///
	/// **Identity:** `ref_bimap(|x| x.clone(), |x| x.clone(), &p)` is equivalent to
	/// `p.clone()`, given `A: Clone, C: Clone`.
	///
	/// **Composition:** `ref_bimap(|x| f2(&f1(x)), |x| g2(&g1(x)), &p)` is equivalent to
	/// `ref_bimap(f2, g2, &ref_bimap(f1, g1, &p))`.
	#[document_examples]
	///
	/// RefBifunctor laws for [`Result`]:
	///
	/// ```
	/// use fp_library::{
	/// 	brands::*,
	/// 	functions::{
	/// 		explicit::bimap,
	/// 		*,
	/// 	},
	/// };
	///
	/// let ok: Result<i32, i32> = Ok(5);
	/// let err: Result<i32, i32> = Err(3);
	///
	/// // Identity: ref_bimap(Clone::clone, Clone::clone, &p) == p.clone()
	/// assert_eq!(bimap::<ResultBrand, _, _, _, _, _, _>((|x: &i32| *x, |x: &i32| *x), &ok), ok,);
	/// assert_eq!(bimap::<ResultBrand, _, _, _, _, _, _>((|x: &i32| *x, |x: &i32| *x), &err), err,);
	///
	/// // Composition: bimap((compose(f1, f2), compose(g1, g2)), &p)
	/// //            = bimap((f2, g2), &bimap((f1, g1), &p))
	/// let f1 = |x: &i32| *x + 1;
	/// let f2 = |x: &i32| *x * 2;
	/// let g1 = |x: &i32| *x + 10;
	/// let g2 = |x: &i32| *x * 3;
	/// assert_eq!(
	/// 	bimap::<ResultBrand, _, _, _, _, _, _>((|x: &i32| f2(&f1(x)), |x: &i32| g2(&g1(x))), &ok),
	/// 	bimap::<ResultBrand, _, _, _, _, _, _>(
	/// 		(f2, g2),
	/// 		&bimap::<ResultBrand, _, _, _, _, _, _>((f1, g1), &ok),
	/// 	),
	/// );
	/// ```
	#[kind(type Of<'a, A: 'a, B: 'a>: 'a;)]
	pub trait RefBifunctor {
		/// Maps functions over the values in the bifunctor context by reference.
		///
		/// Both closures receive references to the values and produce owned output.
		/// The container is borrowed, not consumed.
		#[document_signature]
		///
		#[document_type_parameters(
			"The lifetime of the values.",
			"The type of the first value.",
			"The type of the first result.",
			"The type of the second value.",
			"The type of the second result."
		)]
		///
		#[document_parameters(
			"The function to apply to the first value.",
			"The function to apply to the second value.",
			"The bifunctor instance (borrowed)."
		)]
		///
		#[document_returns(
			"A new bifunctor instance containing the results of applying the functions."
		)]
		#[document_examples]
		///
		/// ```
		/// use fp_library::{
		/// 	brands::*,
		/// 	classes::*,
		/// };
		///
		/// let x: Result<i32, i32> = Ok(5);
		/// let y = ResultBrand::ref_bimap(|e: &i32| *e + 1, |s: &i32| *s * 2, &x);
		/// assert_eq!(y, Ok(10));
		/// ```
		fn ref_bimap<'a, A: 'a, B: 'a, C: 'a, D: 'a>(
			f: impl Fn(&A) -> B + 'a,
			g: impl Fn(&C) -> D + 'a,
			p: &Apply!(<Self as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, A, C>),
		) -> Apply!(<Self as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, B, D>);

		/// Maps a function over the first type argument of the bifunctor by reference.
		///
		/// By-reference variant of [`Bifunctor::map_first`]. The closure receives a reference
		/// to the first value and produces an owned result. Requires `C: Clone` because the
		/// second value must be cloned out of the borrowed container.
		#[document_signature]
		///
		#[document_type_parameters(
			"The lifetime of the values.",
			"The type of the first value.",
			"The type of the first result.",
			"The type of the second value (must be Clone)."
		)]
		///
		#[document_parameters(
			"The function to apply to the first value.",
			"The bifunctor instance (borrowed)."
		)]
		///
		#[document_returns("A new bifunctor instance with the first value transformed.")]
		#[document_examples]
		///
		/// ```
		/// use fp_library::{
		/// 	brands::*,
		/// 	classes::*,
		/// };
		///
		/// let x = Result::<i32, i32>::Err(5);
		/// let y = ResultBrand::ref_map_first(|e: &i32| *e * 2, &x);
		/// assert_eq!(y, Err(10));
		///
		/// let x = Result::<i32, i32>::Ok(5);
		/// let y = ResultBrand::ref_map_first(|e: &i32| *e * 2, &x);
		/// assert_eq!(y, Ok(5));
		/// ```
		fn ref_map_first<'a, A: 'a, B: 'a, C: Clone + 'a>(
			f: impl Fn(&A) -> B + 'a,
			p: &Apply!(<Self as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, A, C>),
		) -> Apply!(<Self as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, B, C>) {
			Self::ref_bimap(f, |c: &C| c.clone(), p)
		}

		/// Maps a function over the second type argument of the bifunctor by reference.
		///
		/// By-reference variant of [`Bifunctor::map_second`]. The closure receives a reference
		/// to the second value and produces an owned result. Requires `A: Clone` because the
		/// first value must be cloned out of the borrowed container.
		#[document_signature]
		///
		#[document_type_parameters(
			"The lifetime of the values.",
			"The type of the first value (must be Clone).",
			"The type of the second value.",
			"The type of the second result."
		)]
		///
		#[document_parameters(
			"The function to apply to the second value.",
			"The bifunctor instance (borrowed)."
		)]
		///
		#[document_returns("A new bifunctor instance with the second value transformed.")]
		#[document_examples]
		///
		/// ```
		/// use fp_library::{
		/// 	brands::*,
		/// 	classes::*,
		/// };
		///
		/// let x = Result::<i32, i32>::Ok(5);
		/// let y = ResultBrand::ref_map_second(|s: &i32| *s * 2, &x);
		/// assert_eq!(y, Ok(10));
		///
		/// let x = Result::<i32, i32>::Err(5);
		/// let y = ResultBrand::ref_map_second(|s: &i32| *s * 2, &x);
		/// assert_eq!(y, Err(5));
		/// ```
		fn ref_map_second<'a, A: Clone + 'a, B: 'a, C: 'a>(
			g: impl Fn(&B) -> C + 'a,
			p: &Apply!(<Self as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, A, B>),
		) -> Apply!(<Self as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, A, C>) {
			Self::ref_bimap(|a: &A| a.clone(), g, p)
		}
	}

	/// Maps functions over the values in the bifunctor context by reference.
	///
	/// Free function version that dispatches to [the type class' associated function][`RefBifunctor::ref_bimap`].
	#[document_signature]
	///
	#[document_type_parameters(
		"The lifetime of the values.",
		"The brand of the bifunctor.",
		"The type of the first value.",
		"The type of the first result.",
		"The type of the second value.",
		"The type of the second result."
	)]
	///
	#[document_parameters(
		"The function to apply to the first value.",
		"The function to apply to the second value.",
		"The bifunctor instance (borrowed)."
	)]
	///
	#[document_returns(
		"A new bifunctor instance containing the results of applying the functions."
	)]
	#[document_examples]
	///
	/// ```
	/// use fp_library::{
	/// 	brands::*,
	/// 	functions::explicit::*,
	/// };
	///
	/// let x = Result::<i32, i32>::Ok(5);
	/// let y = bimap::<ResultBrand, _, _, _, _, _, _>((|e: &i32| *e + 1, |s: &i32| *s * 2), &x);
	/// assert_eq!(y, Ok(10));
	/// ```
	pub fn ref_bimap<'a, Brand: RefBifunctor, A: 'a, B: 'a, C: 'a, D: 'a>(
		f: impl Fn(&A) -> B + 'a,
		g: impl Fn(&C) -> D + 'a,
		p: &Apply!(<Brand as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, A, C>),
	) -> Apply!(<Brand as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, B, D>) {
		Brand::ref_bimap(f, g, p)
	}

	/// Maps a function over the first type argument of the bifunctor by reference.
	///
	/// Free function version that dispatches to [the type class' associated function][`RefBifunctor::ref_map_first`].
	#[document_signature]
	///
	#[document_type_parameters(
		"The lifetime of the values.",
		"The brand of the bifunctor.",
		"The type of the first value.",
		"The type of the first result.",
		"The type of the second value (must be Clone)."
	)]
	///
	#[document_parameters(
		"The function to apply to the first value.",
		"The bifunctor instance (borrowed)."
	)]
	///
	#[document_returns("A new bifunctor instance with the first value transformed.")]
	#[document_examples]
	///
	/// ```
	/// use fp_library::{
	/// 	brands::*,
	/// 	classes::ref_bifunctor::*,
	/// };
	///
	/// let x = Result::<i32, i32>::Err(5);
	/// let y = ref_map_first::<ResultBrand, _, _, _>(|e: &i32| *e * 2, &x);
	/// assert_eq!(y, Err(10));
	/// ```
	pub fn ref_map_first<'a, Brand: RefBifunctor, A: 'a, B: 'a, C: Clone + 'a>(
		f: impl Fn(&A) -> B + 'a,
		p: &Apply!(<Brand as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, A, C>),
	) -> Apply!(<Brand as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, B, C>) {
		Brand::ref_map_first(f, p)
	}

	/// Maps a function over the second type argument of the bifunctor by reference.
	///
	/// Free function version that dispatches to [the type class' associated function][`RefBifunctor::ref_map_second`].
	#[document_signature]
	///
	#[document_type_parameters(
		"The lifetime of the values.",
		"The brand of the bifunctor.",
		"The type of the first value (must be Clone).",
		"The type of the second value.",
		"The type of the second result."
	)]
	///
	#[document_parameters(
		"The function to apply to the second value.",
		"The bifunctor instance (borrowed)."
	)]
	///
	#[document_returns("A new bifunctor instance with the second value transformed.")]
	#[document_examples]
	///
	/// ```
	/// use fp_library::{
	/// 	brands::*,
	/// 	classes::ref_bifunctor::*,
	/// };
	///
	/// let x = Result::<i32, i32>::Ok(5);
	/// let y = ref_map_second::<ResultBrand, _, _, _>(|s: &i32| *s * 2, &x);
	/// assert_eq!(y, Ok(10));
	/// ```
	pub fn ref_map_second<'a, Brand: RefBifunctor, A: Clone + 'a, B: 'a, C: 'a>(
		g: impl Fn(&B) -> C + 'a,
		p: &Apply!(<Brand as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, A, B>),
	) -> Apply!(<Brand as Kind!( type Of<'a, A: 'a, B: 'a>: 'a; )>::Of<'a, A, C>) {
		Brand::ref_map_second(g, p)
	}

	/// [`RefFunctor`] instance for [`BifunctorFirstAppliedBrand`].
	///
	/// Maps over the first type parameter of a bifunctor by reference, delegating to
	/// [`RefBifunctor::ref_bimap`] with [`Clone::clone`] for the second argument.
	/// Requires `Clone` on the fixed second type parameter because the value must be
	/// cloned out of the borrowed container.
	#[document_type_parameters("The bifunctor brand.", "The fixed second type parameter.")]
	impl<Brand: Bifunctor + RefBifunctor, A: Clone + 'static> RefFunctor
		for BifunctorFirstAppliedBrand<Brand, A>
	{
		/// Maps a function over the first type parameter by reference.
		#[document_signature]
		#[document_type_parameters(
			"The lifetime of the values.",
			"The input type.",
			"The output type."
		)]
		#[document_parameters("The function to apply.", "The bifunctor value to map over.")]
		#[document_returns("The mapped bifunctor value.")]
		#[document_examples]
		///
		/// ```
		/// use fp_library::{
		/// 	brands::*,
		/// 	functions::explicit::*,
		/// };
		///
		/// let x = Result::<i32, i32>::Ok(5);
		/// let y = map::<BifunctorFirstAppliedBrand<ResultBrand, i32>, _, _, _, _>(|s: &i32| *s * 2, &x);
		/// assert_eq!(y, Ok(10));
		/// ```
		fn ref_map<'a, B: 'a, C: 'a>(
			func: impl Fn(&B) -> C + 'a,
			fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, B>),
		) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, C>) {
			Brand::ref_bimap(|a: &A| a.clone(), func, fa)
		}
	}

	/// [`RefFunctor`] instance for [`BifunctorSecondAppliedBrand`].
	///
	/// Maps over the second type parameter of a bifunctor by reference, delegating to
	/// [`RefBifunctor::ref_bimap`] with [`Clone::clone`] for the first argument.
	/// Requires `Clone` on the fixed first type parameter because the value must be
	/// cloned out of the borrowed container.
	#[document_type_parameters("The bifunctor brand.", "The fixed first type parameter.")]
	impl<Brand: Bifunctor + RefBifunctor, B: Clone + 'static> RefFunctor
		for BifunctorSecondAppliedBrand<Brand, B>
	{
		/// Maps a function over the second type parameter by reference.
		#[document_signature]
		#[document_type_parameters(
			"The lifetime of the values.",
			"The input type.",
			"The output type."
		)]
		#[document_parameters("The function to apply.", "The bifunctor value to map over.")]
		#[document_returns("The mapped bifunctor value.")]
		#[document_examples]
		///
		/// ```
		/// use fp_library::{
		/// 	brands::*,
		/// 	functions::explicit::*,
		/// };
		///
		/// let x = Result::<i32, i32>::Err(5);
		/// let y = map::<BifunctorSecondAppliedBrand<ResultBrand, i32>, _, _, _, _>(|e: &i32| *e * 2, &x);
		/// assert_eq!(y, Err(10));
		/// ```
		fn ref_map<'a, A: 'a, C: 'a>(
			func: impl Fn(&A) -> C + 'a,
			fa: &Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, A>),
		) -> Apply!(<Self as Kind!( type Of<'a, T: 'a>: 'a; )>::Of<'a, C>) {
			Brand::ref_bimap(func, |b: &B| b.clone(), fa)
		}
	}
}

pub use inner::*;

#[cfg(test)]
mod tests {
	use {
		crate::{
			brands::*,
			functions::explicit::*,
		},
		quickcheck_macros::quickcheck,
	};

	/// RefBifunctor identity law: bimap((Clone::clone, Clone::clone), &p) == p.
	#[quickcheck]
	fn prop_ref_bifunctor_identity(
		a: i32,
		c: i32,
	) -> bool {
		let ok: Result<i32, i32> = Ok(c);
		let err: Result<i32, i32> = Err(a);
		bimap::<ResultBrand, _, _, _, _, _, _>((|x: &i32| *x, |x: &i32| *x), &ok) == ok
			&& bimap::<ResultBrand, _, _, _, _, _, _>((|x: &i32| *x, |x: &i32| *x), &err) == err
	}

	/// RefBifunctor composition law.
	#[quickcheck]
	fn prop_ref_bifunctor_composition(
		a: i32,
		c: i32,
	) -> bool {
		let f1 = |x: &i32| x.wrapping_add(1);
		let f2 = |x: &i32| x.wrapping_mul(2);
		let g1 = |x: &i32| x.wrapping_add(10);
		let g2 = |x: &i32| x.wrapping_mul(3);

		let ok: Result<i32, i32> = Ok(c);
		let err: Result<i32, i32> = Err(a);

		let composed_ok = bimap::<ResultBrand, _, _, _, _, _, _>(
			(|x: &i32| f2(&f1(x)), |x: &i32| g2(&g1(x))),
			&ok,
		);
		let sequential_ok = bimap::<ResultBrand, _, _, _, _, _, _>(
			(f2, g2),
			&bimap::<ResultBrand, _, _, _, _, _, _>((f1, g1), &ok),
		);

		let composed_err = bimap::<ResultBrand, _, _, _, _, _, _>(
			(|x: &i32| f2(&f1(x)), |x: &i32| g2(&g1(x))),
			&err,
		);
		let sequential_err = bimap::<ResultBrand, _, _, _, _, _, _>(
			(f2, g2),
			&bimap::<ResultBrand, _, _, _, _, _, _>((f1, g1), &err),
		);

		composed_ok == sequential_ok && composed_err == sequential_err
	}
}