fix_fn

Macro to create recursive closures (similar to the Y combinator)

4 releases (stable)

1.0.2 May 31, 2020
0.1.0 May 31, 2020
Download history 13/week @ 2024-07-22 29/week @ 2024-07-29 15/week @ 2024-08-05 35/week @ 2024-08-12 8/week @ 2024-08-19 42/week @ 2024-08-26 21/week @ 2024-09-02 123/week @ 2024-09-09 139/week @ 2024-09-16 119/week @ 2024-09-23 58/week @ 2024-09-30 41/week @ 2024-10-07 196/week @ 2024-10-14 88/week @ 2024-10-21 16/week @ 2024-10-28 13/week @ 2024-11-04

322 downloads per month
Used in forward_goto

MIT license

8KB
97 lines

Build Creates.io Docs

fix_fn

This library enables the creation of recursive closures by providing a single macro fix_fn. The functionality is similar to the Y combinator. Recursive closures can have arbitrary amounts of parameters and can capture variables.

use fix_fn::fix_fn;
let fib = fix_fn!(|fib, i: u32| -> u32 {
    if i <= 1 {
           i
    } else {
        // fib will call the closure recursively
        fib(i - 1) + fib(i - 2)
    }
});

assert_eq!(fib(7), 13);

lib.rs:

This library enables the creation of recursive closures by providing a single macro fix_fn. The functionality is similar to the Y combinator. Recursive closures can have arbitrary amounts of parameters and can capture variables.

use fix_fn::fix_fn;

let fib = fix_fn!(|fib, i: u32| -> u32 {
    if i <= 1 {
           i
     } else {
         // fib will call the closure recursively
         fib(i - 1) + fib(i - 2)
     }
 });

assert_eq!(fib(7), 13);

The generated code is not completely abstraction free as it uses one dyn trait (without any boxing) to overcome rust's recursive type limitations. In most cases, however, the optimizer should be able to eliminate any dynamic dispatch.

Unfortunately, mutable recursive closures are not supported.

No runtime deps