clm_rust_core/layer0/functional.rs
1//! Pure function combinators for the Set category (INV-599): identity, compose, pipe, first_match.
2//!
3//! `compose(g, f)(x) == g(f(x))` (right to left) and `pipe(f, g)(x) == g(f(x))` (left to right).
4//! Both are associative with `identity` as unit.
5//!
6//! `first_match(rules, x)` searches an ordered rule table (INV-626). A rule declines with `None` and
7//! answers with `Some(value)`, so a rule whose value type is itself an `Option` can answer `Some(None)`.
8
9/// `id_A(x) = x`.
10pub fn identity<T>(value: T) -> T {
11 value
12}
13
14/// Right-to-left composition: `compose(g, f)(x) == g(f(x))`.
15pub fn compose<A, B, C>(g: impl Fn(B) -> C, f: impl Fn(A) -> B) -> impl Fn(A) -> C {
16 move |value| g(f(value))
17}
18
19/// Left-to-right composition: `pipe(f, g)(x) == g(f(x))`.
20pub fn pipe<A, B, C>(f: impl Fn(A) -> B, g: impl Fn(B) -> C) -> impl Fn(A) -> C {
21 move |value| g(f(value))
22}
23
24/// The answer of the first rule in table order that matches `value`, or `None` when none does.
25pub fn first_match<'r, I: ?Sized, O, R>(rules: impl IntoIterator<Item = &'r R>, value: &I) -> Option<O>
26where
27 R: Fn(&I) -> Option<O> + ?Sized + 'r,
28{
29 rules.into_iter().find_map(|rule| rule(value))
30}