TypeFunction example creatiing a conversion matrix
Adam D. Ruppe
destructionator at gmail.com
Fri Oct 2 19:28:38 UTC 2020
On Friday, 2 October 2020 at 19:13:43 UTC, Bruce Carneal wrote:
> I'm more excited about the ease of learning and better
> debugability of type functions than any compile time
> performance gains but I imagine we'll realize additional
> speedups if type functions are widely adopted. Iteration will
> displace recursion in many places and we'll see a lot more
> "left leaning" code (early returns).
Eh, I'm still pretty skeptical. Notice that the code in this
conversion matrix case is *identical* for type function and
template, except for the header.
template version:
template makeConvMatrix(types...) {
string helper() {
/* same stuff */
}
enum makeConvMatrix = helper();
}
type function version:
string makeConvMatrix(alias[] types ...) {
/* same stuff */
}
And then the call of course has the ! in the template version and
doesn't for the type function version. But the actual function
implementation is identical, the generated binary is identical.
So very little actual difference here aside from the compile
speed+ram mix in different cases.
Using the index pattern too (which actually compiles slower in
most cases), you can get similar looking code:
template Filter(alias Pred, Args...) {
private const(char)[] helper() {
assert(__ctfe);
size_t[Args.length] keep;
size_t pos = 0;
foreach(idx, alias arg; Args)
if(Pred!arg) keep[pos++] = idx;
// generic helper function that expands to
// AliasSeq!(Args[keep[0]], Args[keep[1]], ...)
return makeResult(keep[0 .. pos]);
}
alias Filter = mixin(helper());
}
So again a normal loop building a normal array. Nothing too fancy
here. But in my tests, Phobos' existing implementation is
actually better in CT speed and memory.
The potential I see in the type functions are:
1) faster builds with less memory. I'm putting this under "maybe"
since there's some cases I've tried where it wins, some where it
loses. So I'm skeptical but if it works out it is worth it.
2) making compiler-tuples more natural to work with. Right now
they are a bizarre beast you kinda have to trick into doing
anything. The type function (I have been joking to stefan to call
it Static Tuple Evaluation Function or STEF :P) might make them
feel just like any other array which would be really cool and can
make things nicer that right now must be string mixins at the
usage point.
The current test implementation can't actually do this, but
there's potential in making it work.
3) maybe just educate us on individual pieces we can borrow in
other parts of the language. Its not-unrolled tuple foreach I
think is a win, its CTFE-only nature is a clear win. Paul Backus'
idea of static foreach declarations actually being ref might be
an example of this too. These things might be extracted even if
the overall concept doesn't work out.
We'll see where it goes.
More information about the Digitalmars-d
mailing list