At compile time

bearophile bearophileHUGS at lycos.com
Fri Aug 21 20:18:45 PDT 2009


Don:
>Using CTFE will be a completely different experience after the next release.<

What kind of limits do you want to lift? :-)

I think now LDC uses a compile-time garbage collector (beside the second one in the D runtime and the third one used by LLVM), so using CTFE&templates is better already with LDC.

I like to use CTFE is to create 1D arrays at compile-time. This is a small test, it has the problem of being "fragile": if you change this code just a bit, it doesn't compile anymore. The other problem (with DMD) is that it uses a lot of RAM, even for modern standards of memory.

import std.stdio: writefln;

bool isPrime(int n) {
    if (n < 2)
        return false;
    for (int i = 2; i < n; i++)
        if (n % i == 0)
            return false;
    return true;
}

int[] genPrimes(int n) {
    int[] result;
    for (; n > 1; --n)
        if (isPrime(n))
            result = n ~ result;
    return result;
}

static const auto primes = cast(int[900])genPrimes(7000);

void main() {
    writefln(primes);
}


Currently to do such things I use templat:
http://www.fantascienza.net/leonardo/so/templat.html

With code like this, that's fast and uses small resources, but forces to use two languages:

import std.stdio: writefln;

{{
import textwrap

def find_primes(n):
    if n < 2:
        return []
    primes = [2]
    for i in xrange(2, n+1):
        for j in primes:
            if i % j == 0:
                break
        else:
            primes.append(i)
    return primes

p = find_primes(7000)
out = "const int primes[%d] = %s;" % (len(p), p)
print "\n".join(textwrap.wrap(out, 80, subsequent_indent=" "*4))
}}

void main() {
    writefln(primes);
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list