On Wednesday, 14 March 2012 at 17:35:06 UTC, Don Clugston wrote:
In the last bit of code, why not use CTFE for valid(string s) instead of templates?

bool valid(string s)
{
   foreach(c; s)
   {
     if (c < 'w' || c > 'z') return false;
   }
   return true;
}

In fact you can use CTFE for the other template functions as well.

In the original version I actually did this, but even with -O -inline -release the opDispatchs call didn't get inlined. I thought it was caused by CTFE-code that prevented the inlining.
FWIW, this was the original code using CTFE:
---
import std.algorithm: reduce;
struct Vec {
        double[4] v;
        @property auto X() {return v[0];}
        @property auto Y() {return v[1];}
        @property auto Z() {return v[2];}
        @property auto W() {return v[3];}
        this(double x, double y, double z, double w) {v = [x,y,z,w];}
@property auto opDispatch(string s)() if(s.length <= 4 && reduce!((s,c)=>s && 'w' <= c && c <= 'z')(true, s)) {
                char[] p = s.dup;
                foreach(i; s.length .. 4) p ~= p[$-1];
                int i(char c) {return [3,0,1,2][c-'w'];}
                return Vec(v[i(p[0])], v[i(p[1])], v[i(p[2])], v[i(p[3])]);
        }
}
unittest {
        assert(Vec(5,6,7,8).zyzx == Vec(7, 6, 7, 5));
        assert(Vec(5,6,7,8).zyx  == Vec(7, 6, 5, 5));
        assert(Vec(5,6,7,8).wy   == Vec(8, 6, 6, 6));
        assert(Vec(5,6,7,8).z    == Vec(7, 7, 7, 7));
}
---
(I was using reduce here only to demonstrate D's functional features and nice lambda syntax. Maybe that's what prevented inlining?)

Reply via email to