String Metaprogramming
Nicholas Wilson via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jul 18 09:01:24 PDT 2015
On Saturday, 18 July 2015 at 13:48:20 UTC, Clayton wrote:
> Am new to D programming, am considering it since it supports
> compile-time function execution . My challenge is how can I
> re-implement the function below so that it is fully executed in
> compile-time. The function should result to tabel1 being
> computed at compile-time. There seems to be a lot of mutation
> happening here yet I have heard no mutation should take place
> in meta-programming as it subscribes to functional programming
> paradigm.
> void computeAtCompileTime( ref string pattern ,ref int[char]
> tabel1){
change function signature to
int[char] function(string) or as the char type is the index
probably better of as
int[256] function(string). also probably no need to take pattern
by ref as it is effectively struct{ size_t length; char* ptr;}.
also we aren't going to modify it.
int[256] computeAtCompileTime(string pattern)
{
> int size = to!int(pattern.length) ;
pattern.length is a size_t no need to change its type in another
variable. you are unlikely to be dealing with string longer than
2^32 (also signedness) but w/e
int[256] ret; // implicitly initialised to int.init (i.e.
0)
>
> foreach( c; ALPHABET){
> tabel1[c] = size;
> }
>
> for( int i=0;i<size -1 ; ++i){ //Initialise array
> tabel1[pattern[i]] = size -i-1;
can just foreach over pattern
foreach(i, c; pattern)
ret[c] = pattern.length - i -1;
> pragma(msg, format("reached pattern
> table1[pattern[i]]=(%s) here",
> table1[pattern[i]].stringof ~" v="~ (size
> -i-1).stringof));
> }
> }
if you want this to be not callable at runtime then wrap the main
body (sans variable declaration) with
if (__ctfe)
{
...
}
More information about the Digitalmars-d-learn
mailing list