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
//! Function composition helpers.
//!
//! Utilities for composing and transforming functions and values:
//! - [`compose`] to build `g ∘ f`.
//! - [`pipe`] to pass a value through two functions.
//! - [`tap`] to perform a side-effect without changing the value.
//! - [`identity`] returns its input unchanged.
//! - [`constant`] returns a closure that always yields the same value.
//! - [`noop`] does nothing.
//! - [`negate`] flips a predicate's boolean result.
//! - [`flip`] swaps the first two arguments of a binary function.
//! - [`partial`] captures one argument for later invocation.
//! - [`times`] calls a closure for indices `0..n`.
//! - [`until`] repeatedly applies a step until a predicate holds.
//!
//! Basic examples:
//! ```rust
//! use toolchest::functions::{compose, pipe, tap};
//! use toolchest::functions::compose::{identity, negate, flip, partial, times, until};
//!
//! let double = |x: i32| x * 2;
//! let add1 = |x: i32| x + 1;
//! let h = compose(double, add1); // h(x) = double(add1(x))
//! assert_eq!(h(3), 8);
//!
//! let val = pipe(3, add1, double); // double(add1(3))
//! assert_eq!(val, 8);
//!
//! use std::sync::atomic::{AtomicUsize, Ordering};
//! let seen = AtomicUsize::new(0);
//! let value = tap(10, |_| { seen.fetch_add(1, Ordering::SeqCst); });
//! assert_eq!(value, 10);
//! assert_eq!(seen.load(Ordering::SeqCst), 1);
//!
//! assert_eq!(identity(7), 7);
//! assert_eq!(negate(|x: i32| x > 0)(-1), true);
//!
//! let sub = |a: i32, b: i32| a - b;
//! assert_eq!(flip(sub)(2, 5), 3); // computes sub(5, 2)
//!
//! let add5 = partial(|x: i32| x + 5, 5);
//! assert_eq!(add5(), 10);
//!
//! let mut acc = 0;
//! times(3, |i| acc += i as i32);
//! assert_eq!(acc, 0 + 1 + 2);
//!
//! let res = until(0, |&x| x >= 5, |x| x + 2);
//! assert_eq!(res, 6);
//! ```
/// Compose two functions `g ∘ f`.
///
/// Returns a new function that applies `f` then `g`.
/// Pipe a value through `f` then `g`.
/// Run a side-effect on `value` and return it unchanged.
/// Identity function.
/// Return a closure that always returns a clone of `x`.
/// Do nothing.
/// Logical negation of a predicate.
/// Flip the first two arguments of a function.
/// Partially apply a single argument.
/// Call `f` for indices `0..n`.
/// Repeatedly apply `step` until `pred` is true.