Okay I had a misunderstanding of pure, now I get it, thanks :) and when I changed the code to enum int, the compiler complained about the delete statement too :) so once again thanks :)
On 3 October 2010 13:35, Jonathan M Davis <[email protected]> wrote: > On Sunday 03 October 2010 03:54:06 Emil Madsen wrote: > > So I wrote a program, to find prime numbers, just to check out this pure > > thing; > > > > http://gist.github.com/608493 > > > > However, the program has a runtime of about 5 seconds? - in my mind, if > the > > function is pure, shouldn't the compiler insure that it was evaluated at > > compiletime? - or am I doing it wrong? > > pure != CTFE > > If a function is pure, then it's result can be cached if it's called again > with > the same arguments. So, if you hade a pure sqrt() in an expression like so > > auto x = sqrt(2) + sqrt(2) + sqrt(4); > > then the compiler could choose to do the sqrt(2) call only once and use the > result of the first call again instead of calling it again (though it would > still > have to call do the sqrt(4) call since it's a different argument). It's an > optimization that the compiler may or may not choose to do. I don't know > when > the compiler currently chooses to do it. But regardless, the function is > _not_ > called at compile time. What if it wasn't 2 and 4 but rather function > arguments? > > void myfunc(int x, int y) > { > //... > auto x = sqrt(x) + sqrt(x) + sqrt(y); > //... > } > > The compiler could cache the result of sqrt(x), but it can't do it at > compile > time. If you want a function to be called at compile time, it needs to be > forced. That is, you have to assign the result to a constant. So, > > enum x = sqrt(x) + sqrt(x) + sqrt(y); > > would be done at compile time - assuming that x and y can be known at > compile > time (if they can't then that line won't compile). > > Regardless, purity has _nothing_ to do with CTFE (compile-time function > evaluation). It doesn't even necessarily make it easier for the compiler to > run > the function at compile time if it's pure. > > Now, for your program, assuming that your calcPrimes() function is > CTFE-able, if > you change immutable int to enum or enum int, then it will be run at > compile > time and your program will be a lot faster than 5 seconds because primes > will be > a constant. Of course, if calcPrimes() is _not_ CTFE-able, then you're out > of > lock unless you manage to alter it so that it _is_ CTFE-able. > > Oh, and by the way, don't use delete. It's going to be removed from the > language > and is completely unnecessary. D is garbage collected. If you want to avoid > the > garbage collector, you're going to need to use malloc() and free() (which > definitely are _not_ CTFE-able). > > - Jonathan M Davis > -- // Yours sincerely // Emil 'Skeen' Madsen
