Generic structural recursion

Steven Schveighoffer schveiguy at gmail.com
Thu Jan 27 14:47:25 UTC 2022


On 1/26/22 2:57 PM, H. S. Teoh wrote:
> On Wed, Jan 26, 2022 at 02:06:18PM -0500, Steven Schveighoffer via Digitalmars-d wrote:
> [...]
>> ```d
>> auto interpolate(alias fn, X : double)(ref X val1, ref X val2)
>> {
>>     static if(is(typeof(fn(val1, val2)))) return fn(val1, val2);
>> }
>>
>> auto interpolate(alias fn, X)(ref X val1, ref X val2) if (is(X == struct))
>> {
>>     // loop and recurse
>> }
>> ...
>> ```
> 
> That's what I had, but the problem is that the number of X arguments
> differs from function to function.  So I'd have to duplicate the
> recursion part for each number of arguments, which is bad because
> there's a chance I might change the recursion in the unary version and
> forget to update it in the binary/ternary/etc. version.

Well, this is what I would do then.

```d
auto interpolateImpl(alias fn, Vals...)(ref Vals vals) if (is(Vals[0] == 
double))
{
    return fn(vals);
}

// handle all the other specific types etc.

auto interpolate(alias fn, Vals...)(ref Vals vals) if (allSameType!Vals)
{
    return interpolateImpl!fn(vals);
}
```

Then the only complex one is the one for aggregates.

-Steve


More information about the Digitalmars-d mailing list