/CacheGen

Primary LanguageC#MIT LicenseMIT

CacheGen

Install via Dotnet CLI

dotnet add package CacheGen

A python inspired library for C# to auto implement a Cache function for given method with the help of Source Generator at compile Time.
python code looks like

@lru_cache
def fibbo(x):
   if x==0 or x==1:
       return x
   return fibbo(x-2)+fibbo(x-1)

now C# code equivalent to it will look like

[LruCache]
int Fibbo(int x)
{
   if (x == 1 || x == 0)
       return x;

   return FibboCached(x - 1) + FibboCached(x - 2);
}

notice all recursive call of Fibbo need to be replaced with FibboCached which is auto generated by compiler in following namespaces, make sure to add these on top of file

global using static LibCache.Gen;
using LibCache;

More Examples

string X = "AGGTAB";
string Y = "GXTXAYB";

Console.Write("Length of LCS is "
              + Lcs(X, Y, X.Length, Y.Length));


[LruCache(10000)]
static int Lcs(string X, string Y, int m, int n)
{
    if (m == 0 || n == 0)
        return 0;
    if (X[m - 1] == Y[n - 1])
        return 1 + LcsCached(X, Y, m - 1, n - 1);
    else
        return Math.Max(LcsCached(X, Y, m, n - 1),
                   LcsCached(X, Y, m - 1, n));
}

Recursion print backward

[LruCache]
static void Dfs(int y)
{
    if (y < 0)
        return;

    Console.WriteLine(y);

    DfsCached(y-1);
}