Skip to main content

on

Function on 

Source
pub fn on<A, B, C>(f: impl Fn(B, B) -> C, g: impl Fn(A) -> B, x: A, y: A) -> C
Expand description

Applies a binary function after projecting both arguments through a common function.

on(f, g, x, y) computes f(g(x), g(y)). This is useful for changing the domain of a binary operation.

§Type Signature

forall A B C. ((B, B) -> C, A -> B, A, A) -> C

§Type Parameters

  • A: The type of the original arguments.
  • B: The type of the projected arguments.
  • C: The result type.

§Parameters

  • f: The binary function to apply to the projected values.
  • g: The projection function applied to both arguments.
  • x: The first argument.
  • y: The second argument.

§Returns

The result of applying f to the projected values.

§Examples

use fp_library::functions::*;

// Compare by absolute value
let max_by_abs = on(|a: i32, b: i32| a.max(b), |x: i32| x.abs(), -5, 3);
assert_eq!(max_by_abs, 5);

// Sum the lengths of two strings
let sum_lens = on(|a: usize, b: usize| a + b, |s: &str| s.len(), "hello", "hi");
assert_eq!(sum_lens, 7);