#chain #helper #chaining #function #pattern

ea

Ea is helper macro/function to create function chaining

Show the crate…

2 releases

0.1.2 Mar 17, 2021
0.1.0 Mar 17, 2021

#27 in #chaining

BSD-3-Clause

28KB
287 lines

ea trait library

This trait provide helper function and macro called chain to ease chaining of function where output of first function piped directly as input to another function and so forth.

Use case 1 - Macro chain

use ea::chain;

fn simple_add(a : i32, b : i32, c : i32) -> i32 {
    a + b + c
}

fn pass_through(v : f64) -> f64 {
    v
}

assert_eq!(
    6f64, 
    chain!(
        simple_add(1, 2, 3), 
        |result: i32| {(result as f64).powi(2)}, 
        |sqr: f64| {sqr.powf(0.5)},
        pass_through,
        pass_through
    )
);

Use case 2 - function chain

use ea::chain;

fn simple_add(a : i32, b : i32, c : i32) -> i32 {
    a + b + c
}

fn pass_through(v : f64) -> f64 {
    v
}

assert_eq!(6f64, *chain(simple_add(1, 2, 3))
                        .chain(|result| {(result as f64).powi(2)})
                        .chain(|sqr| sqr.powf(0.5))
                        .chain(pass_through)
                        .chain(pass_through));

lib.rs:

Utilities macro/function to ease function chain to be less verbose.

This crate provide two usage style, a macro chain and a function chain.

Sample showcase

Case 1 chain by using a helper macro

use ea::chain;

fn simple_add(a : i32, b : i32, c : i32) -> i32 {
    a + b + c
}

fn pass_through(v : f64) -> f64 {
    v
}

assert_eq!(
    6f64, 
    chain!(
        simple_add(1, 2, 3), 
        |result: i32| {(result as f64).powi(2)}, 
        |sqr: f64| {sqr.powf(0.5)},
        pass_through,
        pass_through
    )
);
// This macro will expand to:
assert_eq!(
    6f64, 
    pass_through(
        pass_through(
            (|sqr: f64| {sqr.powf(0.5)})(
                (|result: i32| {(result as f64).powi(2)})(
                    simple_add(1, 2, 3)
                )
            )
        )
    )
);

Case 2 chain by using helper function

use ea::chain;

fn simple_add(a : i32, b : i32, c : i32) -> i32 {
    a + b + c
}

fn pass_through(v : f64) -> f64 {
    v
}

assert_eq!(6f64, *chain(simple_add(1, 2, 3))
                        .chain(|result| {(result as f64).powi(2)})
                        .chain(|sqr| sqr.powf(0.5))
                        .chain(pass_through)
                        .chain(pass_through));

No runtime deps