Function rust2fun::combinator::fix

source ·
pub fn fix<T, R, F>(f: F, x: T) -> Rwhere
    F: Fn(&dyn Fn(T) -> R, T) -> R,
Expand description

This function also known as Y combinator allows for recursive functions to be defined in a more natural way. It takes a function that takes a function and a value, and returns a value. The function is then applied to itself, and the value is returned.

Example

use rust2fun::prelude::*;

let factorial = |f: &dyn Fn(u32) -> u32, x| if x == 0 { 1 } else { x * f(x - 1) };
assert_eq!(120, fix(factorial, 5));

let fibonacci = |f: &dyn Fn(u32) -> u32, x| if x < 2 { x } else { f(x - 1) + f(x - 2) };
assert_eq!(8, fix(fibonacci, 6));