std.v2020.algorithm etc[ WAS: Is run.d going to be expand for runtime and the phobos library?]

Steven Schveighoffer schveiguy at gmail.com
Tue Jun 23 12:19:25 UTC 2020


On 6/23/20 5:45 AM, Mathias LANG wrote:
> On Tuesday, 23 June 2020 at 05:26:21 UTC, Andrei Alexandrescu wrote:
>> https://run.dlang.io/is/KgeosK
>>
>> Yah it's kinda surprising innit. For regular functions it's business 
>> as usual - exact match is attempted, conversions are considered etc. 
>> const(T[]) is convertible to const(T)[], nothing new about that.
>>
>> For template functions however, although templates always do exact 
>> match, arrays surreptitiously change their type from const(T[]) to 
>> const(T)[], without a conversion in sight.
>>
>> We need to offer that chance to other ranges if we want them to enjoy 
>> a similar treatment.
> 
> So it's not on function call, but it's about the type being deduced. 
> There's quite a big difference here.

Yes, I agree. It works because of the implicit conversion.

> 
> To me this makes perfect sense: This little peculiarity allows us to 
> reduce the amount of template instantiations. E.g. the following code 
> will only instantiate a single template:
> ```
> void fun2(T)(const T[] a) { pragma(msg, T.stringof); }
> 
> void main() {
>      immutable(int[]) a;
>      fun2(a);
>      int[] b;
>      fun2(b);
> }
> ```

No, that would happen anyway, because in that case, T is stripped of the 
type modifier.

It's this case where it affects the result:

void fun(T)(T a) { pragma(msg, T.stringof); }

void main()
{
    const int[] a;
    const(int)[] b;
    fun(a);
    fun(b);
}

You only get one instantiation there.

The case makes complete sense, because the head is always a different 
memory location (a copy). What we lack is a way to make the head mutable 
of any type via a type modifier, so it's a "special case" in the sense 
that it's possible only on T[] and T*. If we change the special case to 
a general case, then it naturally makes things a lot more usable, and 
gets rid of a lot of the complaints about const ranges.

> 
> In fact I'd love if we extend that to `auto` so the following code would 
> work:
> ```
> immutable(int[]) fun2() { return null; }
> 
> void main() {
>      auto x = fun2();
>      x = fun2(); // Currently `x` is `immutable(int[])` not 
> `immutable(int)[]`
> }
> ```

That would be reasonable too, IMO.

-Steve


More information about the Digitalmars-d mailing list