Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Built-in memoization #23

Open
WhiteBlackGoose opened this issue Sep 11, 2021 · 1 comment
Open

Built-in memoization #23

WhiteBlackGoose opened this issue Sep 11, 2021 · 1 comment
Labels
enhancement New feature or request

Comments

@WhiteBlackGoose
Copy link
Member

WhiteBlackGoose commented Sep 11, 2021

With recursion. Example of code:

PoC

using System;
using System.Collections.Generic;
using static Memes;

var fib = Memoize<int, int>((n, fib) => 
    n switch
    {
        <= 1 => 1,
        var m => fib(n - 1) + fib(n - 2)
    });
Console.WriteLine(fib(40));
                  

public static class Memes
{
    public static Func<TIn, TOut> Memoize<TIn, TOut>(Func<TIn, Func<TIn, TOut>, TOut> func)
    {
        var dic = new Dictionary<TIn, TOut>();
        Func<TIn, TOut> rec = null;
        rec = tin =>
        {
            if (dic.TryGetValue(tin, out var res))
                return res;
            res = func(tin, rec);
            dic[tin] = res;
            return res;
        };
        return rec;
    }
}

API

public static Func<TIn, TOut> Memoize<TIn, TOut>(Func<TIn, Func<TIn, TOut>> func);
public static (Func<TIn1, TOut1>, Func<TIn2, TOut2>) Memoize<TIn1, TIn2, TOut1, TOut2>(Func<TIn1, Func<TIn1, TOut1>, Func<TIn2, TOut2>, TOut1> func1, Func<TIn2, Func<TIn1, TOut1>, Func<TIn2, TOut2>, TOut2> func2);
...
@WhiteBlackGoose WhiteBlackGoose added the enhancement New feature or request label Sep 11, 2021
@WhiteBlackGoose
Copy link
Member Author

Re-consideration with #25: make

prec : (a * (a -> b) -> b) -> a -> b
mrec : (a * (a -> b) -> b) -> a -> b

Where mrec is a memoizing recursor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant