Compile-time fold expression vs recursive template

Nick Treleaven nick at geany.org
Fri Jun 19 17:04:57 UTC 2020


On Saturday, 13 June 2020 at 12:35:58 UTC, Paul Backus wrote:
> This is fundamentally the same kind of thing as the proposed 
> `...` operator--a single AST macro added to the language as a 
> special-case feature, rather than a general facility for doing 
> AST-macro-like things.
>
> Of course, Walter has vetoed full-fledged AST macros, so we 
> won't be seeing those in D any time soon, but I think it is 
> perhaps worth taking a look at which features of AST macros 
> would be useful to have (e.g., not storing intermediate values 
> in the symbol table), and attempting to design a 
> general-purpose facilities that give the programmer access to 
> those features.

I realized my FoldExpression feature invented too much syntax. 
Really all we need is a way to limit what a template can do, i.e. 
(1) not cache instantiations and (2) not declare symbols (aside 
from eponymous symbols) so it can share a single Scope instance 
in dmd. That Scope instance would be reused upon each recursion, 
and only one recursion is allowed in each inner `static if` 
branch. That could be done just by recognizing a special 
identifer __Fold:

template staticIndexOf(alias A, S...)
{
     template __Fold(uint i = 0)
     {
         static if (i != S.length)
         {
             static if (isSame!(A, S[i]))
                 enum __Fold = i;
             else
                 enum __Fold = __Fold!(i + 1);
         }
         else
             enum __Fold = -1;
     }
     alias staticIndexOf = __Fold!();
}

Or we could have separate template attributes for wider 
applicability. In fact those attributes could potentially be 
inferred, although doing that by default might slow compilation. 
Then existing code could even benefit from the new attributes.


More information about the Digitalmars-d mailing list