Skip to main content

compose

Function compose 

Source
pub fn compose<A, B, C>(
    f: impl Fn(B) -> C,
    g: impl Fn(A) -> B,
) -> impl Fn(A) -> C
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 B C. (B -> C, A -> B) -> A -> C

§Type Parameters

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

§Parameters

  • f: The outer function to apply second.
  • g: The inner function to apply first.
  • _: The argument to be passed to the composed function.

§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(add_one, times_two);

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