Skip to main content

karpal_core/
divisible.rs

1use crate::contravariant::PredicateF;
2use crate::divide::Divide;
3#[cfg(all(not(feature = "std"), feature = "alloc"))]
4use alloc::boxed::Box;
5
6/// Divisible: the contravariant analogue of Applicative.
7///
8/// Adds a `conquer` operation (the identity for `divide`), analogous to `pure`.
9///
10/// Laws:
11/// - Left identity: `divide(f, conquer(), fa) ≈ contramap(snd . f, fa)`
12/// - Right identity: `divide(f, fa, conquer()) ≈ contramap(fst . f, fa)`
13pub trait Divisible: Divide {
14    fn conquer<A: 'static>() -> Self::Of<A>;
15}
16
17impl Divisible for PredicateF {
18    fn conquer<A: 'static>() -> Box<dyn Fn(A) -> bool> {
19        Box::new(|_| true)
20    }
21}
22
23#[cfg(test)]
24mod tests {
25    use super::*;
26
27    #[test]
28    fn predicate_conquer() {
29        let p: Box<dyn Fn(i32) -> bool> = PredicateF::conquer();
30        assert!(p(42));
31        assert!(p(-1));
32        assert!(p(0));
33    }
34}
35
36#[cfg(test)]
37mod law_tests {
38    use super::*;
39    use proptest::prelude::*;
40
41    proptest! {
42        // Left identity: divide(|a| ((), a), conquer(), fa)(x) == fa(x)
43        #[test]
44        fn predicate_left_identity(x in any::<i32>()) {
45            let fa: Box<dyn Fn(i32) -> bool> = Box::new(|a| a > 0);
46            let expected = fa(x);
47
48            let fa2: Box<dyn Fn(i32) -> bool> = Box::new(|a| a > 0);
49            let result = PredicateF::divide(
50                |a: i32| ((), a),
51                PredicateF::conquer::<()>(),
52                fa2,
53            );
54            prop_assert_eq!(result(x), expected);
55        }
56
57        // Right identity: divide(|a| (a, ()), fa, conquer())(x) == fa(x)
58        #[test]
59        fn predicate_right_identity(x in any::<i32>()) {
60            let fa: Box<dyn Fn(i32) -> bool> = Box::new(|a| a > 0);
61            let expected = fa(x);
62
63            let fa2: Box<dyn Fn(i32) -> bool> = Box::new(|a| a > 0);
64            let result = PredicateF::divide(
65                |a: i32| (a, ()),
66                fa2,
67                PredicateF::conquer::<()>(),
68            );
69            prop_assert_eq!(result(x), expected);
70        }
71    }
72}