Skip to main content

compose

Function compose 

Source
pub fn compose<A, C, B, F, G>(f: F, g: G) -> impl Fn(A) -> C
where F: Fn(B) -> C, G: Fn(A) -> B,
Expand description

Composes two functions.

Takes two functions, f and g, and returns a new function that applies g to its argument, and then applies f to the result. This is equivalent to the mathematical composition f ∘ g.

§Type Signature

forall a c b. (b -> c, a -> b) -> (a -> c)

§Type Parameters

  • A: The input type of the inner function g.
  • C: The output type of the outer function f.
  • B: The output type of g and the input type of f.
  • F: The type of the outer function.
  • G: The type of the inner function.

§Parameters

  • f: The outer function to apply second.
  • g: The inner function to apply first.

§Returns

A new function that takes an A and returns a C.

§Examples

use fp_library::functions::*;

let add_one = |x: i32| x + 1;
let times_two = |x: i32| x * 2;
let times_two_add_one = compose::<i32, i32, _, _, _>(add_one, times_two);

// 3 * 2 + 1 = 7
assert_eq!(
    times_two_add_one(3),
    7
);