Memoization in compile-time
Dennis Ritchie via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Mar 12 18:23:07 PDT 2015
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))
More information about the Digitalmars-d-learn
mailing list