Crate composable

Source
Expand description

Simple crate to allow for easy composition of “functional traits” and/or functions and/or closures.

Functional traits are defined by the Composable trait and its apply method.

Two or more composables can be composed through different means:

Basic example:

use composable::*;
 
struct AddTo { addend: usize }
 
impl Composable<usize, usize> for AddTo {
    fn apply(&self, input: usize) -> Result<usize> { Ok(input + self.addend) }
}
 
fn demo() -> Result<()> {
    let increment = AddTo { addend: 1 };
    let square = |x: usize| Ok(x * x);
    let composition = compose(increment, square);
    let result = composition.apply(2)?;
    assert_eq!(result, 9);
    Ok(())
}

It is also possible to combine a composable of type X->(Y, V1) with another composable of type Y->(Z, V2) into a composable of type X->(Z, (V1, V2)). This operation is provided by compose_t() and composed_t!.

For example:

use composable::*;
 
struct AddToMsg { addend: usize }
 
impl Composable<usize, (usize, String)> for AddToMsg {
    fn apply(&self, input: usize) -> Result<(usize, String)> { 
        Ok((input + self.addend, "hello".to_string())) 
    }
}
 
fn demo_t() -> Result<()> {
    let increment = AddToMsg { addend: 1 };
    let square = |x: usize| Ok(((x * x), "world".to_string()));
    let composition = compose_t(increment, square);
    let (result, (msg1, msg2)) = composition.apply(2)?;
    assert_eq!(result, 9);
    assert_eq!(msg1, "hello");
    assert_eq!(msg2, "world");
    Ok(())
}

The symmetric operation is provided by compose_rt() and the composed_rt! macro.

Macros§

composed
Macro-rules for easy composition (owned)
composed_rt
Macro-rules for easy composition (with input tuples)
composed_t
Macro-rules for easy composition (with output tuples)

Structs§

Print
Utility Composable that prints the passed value and returns it untouched

Traits§

Composable
Defines a “functional” (composable) trait

Functions§

compose
Composition
compose_rt
Special composition that combines tuple input values
compose_t
Special composition that combines tuple output values

Type Aliases§

Result