Function tool::fix[][src]

pub fn fix<A, B, F>(
    f: F
) -> impl Fn(A) -> B where
    F: Fn(&Fn(A) -> B, A) -> B, 

A Y-Combinator.

Takes a function f and returns a fixpoint of f.

In English, this allows you to define a recursive closure, something that's normally quite hard to do in rust. Rather than try to explain it, here's an illustration that should speak for itself (as long as you know the recursive definition of Fibonacci numbers).

use tool::prelude::*;

let fib = fix(|f, x| {
    if x == 0 || x == 1 {
        x
    } else {
        // `f` is `fib`
        f(x - 1) + f(x - 2)
    }
});
assert_eq!(55, fib(10));