Memoization in compile-time

Rikki Cattermole via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Mar 12 19:38:14 PDT 2015


On 13/03/2015 2:23 p.m., Dennis Ritchie wrote:
> Is it possible to run this code in compile-time?
>
> import std.stdio, std.functional;
>
> ulong fact(ulong n)
> {
>      alias mfact = memoize!fact;
>      return n < 2 ? 1 : n * mfact(n - 1);
> }
>
> void main() {
>
>      writeln(fact(10));
> }
>
> In CommonLisp variable *factorial-cache* available in CT, and RT.
> Moreover, in the compiler environment of your *factorial-cache* and RT.
> Thus we memoires as calculations in CT (constants), and RT.
>
> (eval-always
>    (defparameter *factorial-cache* (make-hash-table))
>    (defun factorial (n)
>      (if (< n 1)
>          1
>          (setf (gethash n *factorial-cache*) (* n (factorial (1- n)))))))
>
> (define-compiler-macro factorial (&whole whole n)
>    (if (constantp n) (factorial n) whole))

Here is an example I have in my Developing with compile time in mind 
book[0]:

size_t factorial(size_t n) pure {
	assert(n < 11);
	if (n == 0) {
		return 1;
	} else {
		return n * factorial(n - 1);
	}
}

static assert(factorial(5) == 120);

Notice how it is in a static assert? Yeah that is at compile time.
You could assign it to e.g. an enum. Or force it over using 
meta-programming.

If you haven't already, I would strongly recommend that you read my book 
on the subject.

[0] https://leanpub.com/ctfe


More information about the Digitalmars-d-learn mailing list