Memoization in compile-time
Dennis Ritchie via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Mar 13 06:05:54 PDT 2015
On Friday, 13 March 2015 at 12:58:13 UTC, Meta wrote:
> On Friday, 13 March 2015 at 12:49:48 UTC, Dennis Ritchie wrote:
>> On Friday, 13 March 2015 at 02:38:18 UTC, Rikki Cattermole
>> wrote:
>>> You could assign it to e.g. an enum. Or force it over using
>>> meta-programming.
>>
>> And this code can be rewritten to D?
>>
>> template <int n>
>> struct Factorial
>> {
>> enum { value = n * Factorial<n - 1>::value };
>> };
>>
>> template <>
>> struct Factorial<0>
>> {
>> enum { value = 1 };
>> };
>>
>> int main()
>> {
>> constexpr auto x = Factorial<5>::value;
>> constexpr auto y = Factorial<7>::value;
>> }
>
> You can translate it directly:
>
> template Factorial(int n)
> {
> static if (n == 0)
> {
> enum Factorial = 1;
> }
> else static if (n > 0)
> {
> enum Factorial = n * Factorial!(n - 1);
> }
> else
> {
> static assert(false, "n cannot be negative");
> }
> }
>
> int main()
> {
> //Calculated at compile time
> auto x = Factorial!5;
> auto y = Factorial!7;
> }
>
>
>
>
> However, it's much easier to just write a function and decide
> whether you want to calculate its value at runtime or compile
> time.
>
> int factorial(int n)
> in
> {
> assert(n >= 0, "n cannot be 0");
> }
> body
> {
> return n == 0 ? 1 : n * factorial(n - 1);
> }
>
> void main()
> {
> //Evaluated at compile time
> enum x = factorial(5);
>
> //Evaluated at runtime
> auto y = factorial(7);
> }
Thanks.
More information about the Digitalmars-d-learn
mailing list