Compiletime Table
D_Learner via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Aug 14 13:36:34 PDT 2015
On Thursday, 13 August 2015 at 19:54:18 UTC, anonymous wrote:
> On Thursday, 13 August 2015 at 19:13:55 UTC, D_Learner wrote:
>> [...]
>
> I think you may have some fundamental misunderstandings
> regarding CTFE, templates, etc. Your code seems to be half-way
> between a template-based and a CTFE-based solution.
>
> The simple way to do compile-time computation in D is CTFE
> (Compile Time Function Evaluation). That is, you write a pure
> function that can be evaluated both at run-time and at
> compile-time. CTFE doesn't need template parameters.
>
> Here's some code that should do the same as yours and is
> compatible with CTFE:
>
> ----
> import std.conv: to;
> import std.stdio;
>
> int[char] calculatebmBc(string pattern) pure
> {
> const int size = to!int(pattern.length);
> int[char] result;
>
> foreach(i; 0 .. size - 1)
> {
> result[pattern[i]] = to!int(size - i - 1);
> }
>
> return result;
> }
>
> void main()
> {
> auto bmBc = calculatebmBc("GCAGAGAG");
> enum bmBcTable = calculatebmBc("GCAGAGAG");
> }
> ----
>
> The key is that calculatebmBc is pure, i.e. it doesn't read or
> write any module-level mutables.
>
> I touched some things here and here I didn't like that are not
> related to purity/CTFE.
>
> Adam D. Ruppe already mentioned an issue with associative
> arrays: This doesn't work:
> ----
> static foo = calculatebmBc("GCAGAGAG");
> ----
> It's annoying, but if you need that you have to use some other
> data structure. See Adam's post.
Thanks so much for the advice, it works fine. Just experimented
with the code . I had no idea about it. My mind had the some
pre-occupation that compile-time execution is only achievable
through templates. Had no idea about pure functions...awesone ,
code. Thanks again for the clear explanation.
More information about the Digitalmars-d-learn
mailing list