asc-community / HonkSharp

Some wrappers and API and methods for fast and convenient declarative coding in C#
47 stars 4 forks source link

Primitive recursion #25

Closed WhiteBlackGoose closed 2 years ago

WhiteBlackGoose commented 2 years ago

For recursion for anonymous functions:

var fact = Prec((int i, Func<int, int> fact)
        => i == 0 ? 1 : i * fact(i - 1)
);

PoC implementation:

static Func<TIn, TOut> Prec<TIn, TOut>(Func<TIn, Func<TIn, TOut>, TOut> rec)
{
    TOut Hehe(TIn input)
    {
        return rec(input, static i => Hehe(i)); // do not eta reduce!
    }

    return Hehe;
}

Together with memoization, we could anonymously define, say, fibonacci:

var fib = Mem(Prec(int i, Func<int, int> fib) => i switch
    0 or 1 => 1,
    var n => fib(i - 1) + fib(i - 2)
}));
WhiteBlackGoose commented 2 years ago

Full impl of both

WhiteBlackGoose commented 2 years ago

(it doesn't work btw, we will have to merge mem and prec into ... mrec?)

WhiteBlackGoose commented 2 years ago

Basically dup of #23