March 13, 2015
On 03/13/2015 06:51 AM, Dennis Ritchie wrote:
> And you can somehow memoization stuff at compile time?

Scarily simple. :D

import std.stdio;

enum N = 15;
enum int[] factorials = memoizeFactorials(N);

int[] memoizeFactorials(int n)
{
    if (!__ctfe) {
        // Make sure that this function is never called at run time
        assert(false);
    }

    int[] result = new int[n];

    result[0] = 1;

    foreach (i; 1 .. n) {
        result[i] = result[i - 1] * i;
    }

    return result;
}

int fact(int n)
{
    return factorials[n];
}

void main()
{
    foreach (i; 0 .. N) {
        writeln(fact(i));
    }
}

Ali

March 13, 2015
On 03/13/2015 11:28 AM, Ali Çehreli wrote:

> enum int[] factorials = memoizeFactorials(N);

Oops! That's generally a trap! The array better be 'static' because a manifest constant like 'enum factorials' would be inserted everywhere it is used. (Similar to a C macro.)

I've been scratching my head why the assertion below was failing.

It sould be 'static':

static int[] factorials = memoizeFactorials(N);

If it's an enum, the following assert will fail:

    foreach (i; 0 .. N) {
        assert(factorials.ptr + i == &(factorials[i]));
    }

Make it a 'static', it will pass because then there will be just one factorials array.

Ali

March 13, 2015
On Friday, 13 March 2015 at 18:38:16 UTC, Ali Çehreli wrote:
> On 03/13/2015 11:28 AM, Ali Çehreli wrote:
>
> > enum int[] factorials = memoizeFactorials(N);
>
> Oops! That's generally a trap! The array better be 'static' because a manifest constant like 'enum factorials' would be inserted everywhere it is used. (Similar to a C macro.)
>
> I've been scratching my head why the assertion below was failing.
>
> It sould be 'static':
>
> static int[] factorials = memoizeFactorials(N);
>
> If it's an enum, the following assert will fail:
>
>     foreach (i; 0 .. N) {
>         assert(factorials.ptr + i == &(factorials[i]));
>     }
>
> Make it a 'static', it will pass because then there will be just one factorials array.
>
> Ali

Thanks.

And you can make the same memoized variable was available at compile time and at run time? :)
March 13, 2015
On 03/13/2015 12:09 PM, Dennis Ritchie wrote:

> And you can make the same memoized variable was available at compile
> time and at run time? :)

Yes, run-time is always possible and if it can be computed at compile time, compile-time is also possible.

Ali

March 13, 2015
On Friday, 13 March 2015 at 21:16:24 UTC, Ali Çehreli wrote:
> On 03/13/2015 12:09 PM, Dennis Ritchie wrote:
>
> > And you can make the same memoized variable was available at
> compile
> > time and at run time? :)
>
> Yes, run-time is always possible and if it can be computed at compile time, compile-time is also possible.

Thanks.
1 2
Next ›   Last »