Skip to content

Instantly share code, notes, and snippets.

@sibu-github
Created April 14, 2022 03:31
Show Gist options
  • Save sibu-github/2b1f973cabfe733bed9d93c76941cc0c to your computer and use it in GitHub Desktop.
Save sibu-github/2b1f973cabfe733bed9d93c76941cc0c to your computer and use it in GitHub Desktop.
Compose Higher Order Function in Rust
// compose a Higher Order Function with two function as input parameter
// so the compose function takes two parameters f1, f2 and returns a function f3
// f1, f2 & f3 - all functions takea one parameter i32 and returns a value i32
#[allow(dead_code)]
fn compose(f1: impl Fn(i32) -> i32, f2: impl Fn(i32) -> i32) -> impl Fn(i32) -> i32 {
move |x: i32| f2(f1(x))
}
#[cfg(test)]
mod tests {
use super::*;
fn add_two(n: i32) -> i32 {
n + 2
}
fn multiply_three(n: i32) -> i32 {
n * 3
}
fn divide_two(n: i32) -> i32 {
n / 2
}
fn square(n: i32) -> i32 {
n.pow(2)
}
fn cube(n: i32) -> i32 {
n.pow(3)
}
#[test]
fn case_1() {
let composed = compose(add_two, add_two);
assert_eq!(composed(2), 6);
assert_eq!(composed(0), 4);
assert_eq!(composed(-4), 0);
}
#[test]
fn case_2() {
let composed = compose(add_two, multiply_three);
assert_eq!(composed(0), 6);
assert_eq!(composed(2), 12);
assert_eq!(composed(-12), -30);
}
#[test]
fn case_3() {
let composed = compose(multiply_three, divide_two);
assert_eq!(composed(0), 0);
assert_eq!(composed(2), 3);
assert_eq!(composed(5), 7);
}
#[test]
fn case_4() {
let composed = compose(square, cube);
assert_eq!(composed(0), 0);
assert_eq!(composed(2), 64);
assert_eq!(composed(5), 15625);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment