orlando-transducers 0.5.1

High-performance transducers, functional optics, and reactive primitives — with WebAssembly bindings for JavaScript
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
//! Logic functions for predicate composition and conditional transformations.
//!
//! This module provides utilities for combining predicates and creating conditional
//! transformations, inspired by Ramda's logic functions.

use crate::step::Step;
use crate::transducer::Transducer;
use std::marker::PhantomData;
use std::rc::Rc;

// ========================================
// Type Aliases
// ========================================

/// Type alias for a boxed predicate function
pub type BoxedPredicate<T> = Box<dyn Fn(&T) -> bool>;

/// Type alias for a vector of boxed predicates
pub type PredicateVec<T> = Vec<BoxedPredicate<T>>;

// ========================================
// Predicate Combinators
// ========================================

/// Combines two predicates with AND logic.
///
/// Returns a new predicate that is true only when both input predicates are true.
///
/// # Examples
///
/// ```
/// use orlando_transducers::logic::both;
///
/// let is_positive = |x: &i32| *x > 0;
/// let is_even = |x: &i32| x % 2 == 0;
/// let is_positive_even = both(is_positive, is_even);
///
/// assert!(is_positive_even(&4));
/// assert!(!is_positive_even(&3));
/// assert!(!is_positive_even(&-2));
/// ```
pub fn both<T, P1, P2>(pred1: P1, pred2: P2) -> impl Fn(&T) -> bool
where
    P1: Fn(&T) -> bool,
    P2: Fn(&T) -> bool,
{
    move |x| pred1(x) && pred2(x)
}

/// Combines two predicates with OR logic.
///
/// Returns a new predicate that is true when either input predicate is true.
///
/// # Examples
///
/// ```
/// use orlando_transducers::logic::either;
///
/// let is_small = |x: &i32| *x < 10;
/// let is_large = |x: &i32| *x > 100;
/// let is_extreme = either(is_small, is_large);
///
/// assert!(is_extreme(&5));
/// assert!(is_extreme(&200));
/// assert!(!is_extreme(&50));
/// ```
pub fn either<T, P1, P2>(pred1: P1, pred2: P2) -> impl Fn(&T) -> bool
where
    P1: Fn(&T) -> bool,
    P2: Fn(&T) -> bool,
{
    move |x| pred1(x) || pred2(x)
}

/// Negates a predicate.
///
/// Returns a new predicate that returns true when the input predicate returns false,
/// and vice versa.
///
/// # Examples
///
/// ```
/// use orlando_transducers::logic::complement;
///
/// let is_even = |x: &i32| x % 2 == 0;
/// let is_odd = complement(is_even);
///
/// assert!(is_odd(&3));
/// assert!(!is_odd(&4));
/// ```
pub fn complement<T, P>(pred: P) -> impl Fn(&T) -> bool
where
    P: Fn(&T) -> bool,
{
    move |x| !pred(x)
}

/// Combines multiple predicates with AND logic.
///
/// Returns a new predicate that is true only when ALL input predicates are true.
/// Short-circuits on the first false predicate.
///
/// # Examples
///
/// ```
/// use orlando_transducers::logic::{all_pass, PredicateVec};
///
/// let predicates: PredicateVec<i32> = vec![
///     Box::new(|x: &i32| *x > 0),
///     Box::new(|x: &i32| *x < 100),
///     Box::new(|x: &i32| x % 2 == 0),
/// ];
///
/// let is_valid = all_pass(predicates);
///
/// assert!(is_valid(&50));  // positive, < 100, even
/// assert!(!is_valid(&3));  // positive, < 100, but odd
/// assert!(!is_valid(&150)); // positive, even, but >= 100
/// ```
pub fn all_pass<T>(predicates: PredicateVec<T>) -> impl Fn(&T) -> bool {
    move |x| predicates.iter().all(|pred| pred(x))
}

/// Combines multiple predicates with OR logic.
///
/// Returns a new predicate that is true when ANY input predicate is true.
/// Short-circuits on the first true predicate.
///
/// # Examples
///
/// ```
/// use orlando_transducers::logic::{any_pass, PredicateVec};
///
/// let predicates: PredicateVec<i32> = vec![
///     Box::new(|x: &i32| *x == 0),
///     Box::new(|x: &i32| x % 10 == 0),
///     Box::new(|x: &i32| *x > 1000),
/// ];
///
/// let is_special = any_pass(predicates);
///
/// assert!(is_special(&0));    // equals 0
/// assert!(is_special(&50));   // divisible by 10
/// assert!(is_special(&2000)); // > 1000
/// assert!(!is_special(&7));   // none of the above
/// ```
pub fn any_pass<T>(predicates: PredicateVec<T>) -> impl Fn(&T) -> bool {
    move |x| predicates.iter().any(|pred| pred(x))
}

// ========================================
// Conditional Transducers
// ========================================

/// Conditional transformation - applies transform only when predicate is true.
///
/// When the predicate is false, the value passes through unchanged.
///
/// # Examples
///
/// ```
/// use orlando_transducers::logic::When;
/// use orlando_transducers::collectors::to_vec;
///
/// let double_if_positive = When::new(|x: &i32| *x > 0, |x: i32| x * 2);
/// let result = to_vec(&double_if_positive, vec![-1, 2, -3, 4]);
/// assert_eq!(result, vec![-1, 4, -3, 8]);
/// ```
pub struct When<P, F, T> {
    predicate: Rc<P>,
    transform: Rc<F>,
    _phantom: PhantomData<T>,
}

impl<P, F, T> When<P, F, T>
where
    P: Fn(&T) -> bool,
    F: Fn(T) -> T,
{
    pub fn new(predicate: P, transform: F) -> Self {
        When {
            predicate: Rc::new(predicate),
            transform: Rc::new(transform),
            _phantom: PhantomData,
        }
    }
}

impl<P, F, T> Transducer<T, T> for When<P, F, T>
where
    P: Fn(&T) -> bool + 'static,
    F: Fn(T) -> T + 'static,
    T: Clone + 'static,
{
    #[inline(always)]
    fn apply<Acc, R>(&self, reducer: R) -> Box<dyn Fn(Acc, T) -> Step<Acc>>
    where
        R: Fn(Acc, T) -> Step<Acc> + 'static,
        Acc: 'static,
    {
        let predicate = Rc::clone(&self.predicate);
        let transform = Rc::clone(&self.transform);

        Box::new(move |acc, val| {
            if predicate(&val) {
                reducer(acc, transform(val))
            } else {
                reducer(acc, val)
            }
        })
    }
}

/// Conditional transformation - applies transform only when predicate is false.
///
/// When the predicate is true, the value passes through unchanged.
/// This is the inverse of `When`.
///
/// # Examples
///
/// ```
/// use orlando_transducers::logic::Unless;
/// use orlando_transducers::collectors::to_vec;
///
/// let zero_if_negative = Unless::new(|x: &i32| *x > 0, |_| 0);
/// let result = to_vec(&zero_if_negative, vec![-1, 2, -3, 4]);
/// assert_eq!(result, vec![0, 2, 0, 4]);
/// ```
pub struct Unless<P, F, T> {
    predicate: Rc<P>,
    transform: Rc<F>,
    _phantom: PhantomData<T>,
}

impl<P, F, T> Unless<P, F, T>
where
    P: Fn(&T) -> bool,
    F: Fn(T) -> T,
{
    pub fn new(predicate: P, transform: F) -> Self {
        Unless {
            predicate: Rc::new(predicate),
            transform: Rc::new(transform),
            _phantom: PhantomData,
        }
    }
}

impl<P, F, T> Transducer<T, T> for Unless<P, F, T>
where
    P: Fn(&T) -> bool + 'static,
    F: Fn(T) -> T + 'static,
    T: Clone + 'static,
{
    #[inline(always)]
    fn apply<Acc, R>(&self, reducer: R) -> Box<dyn Fn(Acc, T) -> Step<Acc>>
    where
        R: Fn(Acc, T) -> Step<Acc> + 'static,
        Acc: 'static,
    {
        let predicate = Rc::clone(&self.predicate);
        let transform = Rc::clone(&self.transform);

        Box::new(move |acc, val| {
            if !predicate(&val) {
                reducer(acc, transform(val))
            } else {
                reducer(acc, val)
            }
        })
    }
}

/// Branch on condition - applies different transforms based on predicate.
///
/// If the predicate is true, applies `on_true` transform.
/// If the predicate is false, applies `on_false` transform.
///
/// # Examples
///
/// ```
/// use orlando_transducers::logic::IfElse;
/// use orlando_transducers::collectors::to_vec;
///
/// let abs_with_sign = IfElse::new(
///     |x: &i32| *x >= 0,
///     |x: i32| x * 2,      // double if positive
///     |x: i32| x / 2       // halve if negative
/// );
/// let result = to_vec(&abs_with_sign, vec![-4, 3, -6, 5]);
/// assert_eq!(result, vec![-2, 6, -3, 10]);
/// ```
pub struct IfElse<P, F1, F2, T> {
    predicate: Rc<P>,
    on_true: Rc<F1>,
    on_false: Rc<F2>,
    _phantom: PhantomData<T>,
}

impl<P, F1, F2, T> IfElse<P, F1, F2, T>
where
    P: Fn(&T) -> bool,
    F1: Fn(T) -> T,
    F2: Fn(T) -> T,
{
    pub fn new(predicate: P, on_true: F1, on_false: F2) -> Self {
        IfElse {
            predicate: Rc::new(predicate),
            on_true: Rc::new(on_true),
            on_false: Rc::new(on_false),
            _phantom: PhantomData,
        }
    }
}

impl<P, F1, F2, T> Transducer<T, T> for IfElse<P, F1, F2, T>
where
    P: Fn(&T) -> bool + 'static,
    F1: Fn(T) -> T + 'static,
    F2: Fn(T) -> T + 'static,
    T: Clone + 'static,
{
    #[inline(always)]
    fn apply<Acc, R>(&self, reducer: R) -> Box<dyn Fn(Acc, T) -> Step<Acc>>
    where
        R: Fn(Acc, T) -> Step<Acc> + 'static,
        Acc: 'static,
    {
        let predicate = Rc::clone(&self.predicate);
        let on_true = Rc::clone(&self.on_true);
        let on_false = Rc::clone(&self.on_false);

        Box::new(move |acc, val| {
            if predicate(&val) {
                reducer(acc, on_true(val))
            } else {
                reducer(acc, on_false(val))
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::collectors::to_vec;

    #[test]
    fn test_both() {
        let is_positive = |x: &i32| *x > 0;
        let is_even = |x: &i32| x % 2 == 0;
        let is_positive_even = both(is_positive, is_even);

        assert!(is_positive_even(&4));
        assert!(!is_positive_even(&3));
        assert!(!is_positive_even(&-2));
    }

    #[test]
    fn test_either() {
        let is_small = |x: &i32| *x < 10;
        let is_large = |x: &i32| *x > 100;
        let is_extreme = either(is_small, is_large);

        assert!(is_extreme(&5));
        assert!(is_extreme(&200));
        assert!(!is_extreme(&50));
    }

    #[test]
    fn test_complement() {
        let is_even = |x: &i32| x % 2 == 0;
        let is_odd = complement(is_even);

        assert!(is_odd(&3));
        assert!(!is_odd(&4));
    }

    #[test]
    fn test_all_pass() {
        let predicates: PredicateVec<i32> = vec![
            Box::new(|x: &i32| *x > 0),
            Box::new(|x: &i32| *x < 100),
            Box::new(|x: &i32| x % 2 == 0),
        ];

        let is_valid = all_pass(predicates);

        assert!(is_valid(&50));
        assert!(!is_valid(&3));
        assert!(!is_valid(&150));
    }

    #[test]
    fn test_any_pass() {
        let predicates: PredicateVec<i32> = vec![
            Box::new(|x: &i32| *x == 0),
            Box::new(|x: &i32| x % 10 == 0),
            Box::new(|x: &i32| *x > 1000),
        ];

        let is_special = any_pass(predicates);

        assert!(is_special(&0));
        assert!(is_special(&50));
        assert!(is_special(&2000));
        assert!(!is_special(&7));
    }

    #[test]
    fn test_when() {
        let double_if_positive = When::new(|x: &i32| *x > 0, |x: i32| x * 2);
        let result = to_vec(&double_if_positive, vec![-1, 2, -3, 4]);
        assert_eq!(result, vec![-1, 4, -3, 8]);
    }

    #[test]
    fn test_unless() {
        let zero_if_negative = Unless::new(|x: &i32| *x > 0, |_| 0);
        let result = to_vec(&zero_if_negative, vec![-1, 2, -3, 4]);
        assert_eq!(result, vec![0, 2, 0, 4]);
    }

    #[test]
    fn test_if_else() {
        let abs_with_sign = IfElse::new(|x: &i32| *x >= 0, |x: i32| x * 2, |x: i32| x / 2);
        let result = to_vec(&abs_with_sign, vec![-4, 3, -6, 5]);
        assert_eq!(result, vec![-2, 6, -3, 10]);
    }
}