1 unstable release

0.1.0 Jun 28, 2020

#2150 in Procedural macros

MIT license

6KB

memor: Simple memoization macro for rust

Usage

Just add #[memo] to your function.

use memor::memo;
#[memo]
fn fib(n: i64) -> i64 {
    if n == 0 || n == 1 {
        n
    } else {
        fib(n - 1) + fib(n - 2)
    }
}

assert_eq!(12586269025, fib(50));

Various functions can be memoized. Because the arguments are saved as the keys of std::collections::HashMap internally, this macro can be applied to functions all of whose arguments implements Eq + Hash.

use memor::memo;
#[derive(Hash, Eq, PartialEq)]
struct Foo {
    a: usize,
    b: usize,
}

#[memo]
fn foo(Foo { a, b }: Foo, c: usize) -> usize {
    if a == 0 || b == 0 || c == 0 {
        1
    } else {
        foo(Foo { a, b: b - 1 }, c)
            .wrapping_add(foo(Foo { a: a - 1, b }, c))
            .wrapping_add(foo(Foo { a, b }, c - 1))
    }
}

assert_eq!(foo(Foo { a: 50, b: 50 }, 50), 6753084261833197057);

lib.rs:

An attribute macro to memoize function calls

Usage

Just add #[memo] to your function.

use memor::memo;
#[memo]
fn fib(n: i64) -> i64 {
    if n == 0 || n == 1 {
        n
    } else {
        fib(n - 1) + fib(n - 2)
    }
}

assert_eq!(12586269025, fib(50));

Various functions can be memoized. Because the arguments are saved into keys of std::collections::HashMap internally, this macro can be applied to functions all of whose arguments implments Hash and Eq.

use memor::memo;
#[derive(Hash, Eq, PartialEq)]
struct Foo {
    a: usize,
    b: usize,
}

#[memo]
fn foo(Foo { a, b }: Foo, c: usize) -> usize {
    if a == 0 || b == 0 || c == 0 {
        1
    } else {
        foo(Foo { a, b: b - 1 }, c)
            .wrapping_add(foo(Foo { a: a - 1, b }, c))
            .wrapping_add(foo(Foo { a, b }, c - 1))
    }
}

assert_eq!(foo(Foo { a: 50, b: 50 }, 50), 6753084261833197057);

Dependencies

~1.5MB
~32K SLoC