Templates problem

Lodovico Giaretta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 7 02:04:20 PDT 2016


On Wednesday, 7 September 2016 at 08:19:39 UTC, Russel Winder 
wrote:
> On Tue, 2016-09-06 at 14:50 +0000, Lodovico Giaretta via 
> Digitalmars-d- learn wrote:
>> 
> […]
>>  From a quick look, it looks like `results` is a 
>> `const(TickDuration[3])`, that is a fixed-length array. And 
>> fixed-length arrays aren't ranges. If you explicitly slice 
>> them, they become dynamic arrays, which are ranges.
>> 
>> So the solution is to call `map` with `results[]` instead of 
>> `results`.
>
> So trying with results[] leads to:
>
> run_checks.d(21): Error: mutable method 
> std.algorithm.iteration.MapResult!(function (TickDuration t) => 
> to(t).total(), const(TickDuration)[]).MapResult.opIndex is not 
> callable using a const object
> run_checks.d(21): Error: mutable method 
> std.algorithm.iteration.MapResult!(function (TickDuration t) => 
> to(t).total(), const(TickDuration)[]).MapResult.opIndex is not 
> callable using a const object
> run_checks.d(21): Error: mutable method 
> std.algorithm.iteration.MapResult!(function (TickDuration t) => 
> to(t).total(), const(TickDuration)[]).MapResult.opIndex is not 
> callable using a const object
>
> yes, the message is repeated three times, for unknown reason. 
> Possibly because the compiler is fairly certain I am not going 
> to believe it.
>
> So the upshot of this is that I can't work with const data, 
> which is dreadful in these days of single assignment being the 
> way of doing things.
>
> So what is the way of constructing a range from a const array? 
> If it involves copying then D is doomed.
>
> And yes I am under stress as I am trying to pitch D to Python 
> people next week.

You have your const fixed-length array. You slice it and you 
obtain a const range to feed map. Now map will not return you an 
array. Because most of the time you don't need it. It will return 
you a range that lazily computes its elements on demand. No 
memory allocation at all. You can do a foreach on that range. If 
you need to access those elements more than once, instead of 
recomputing each of them every time it is accessed, you can store 
the results of the map. You simply have to use .array on the map 
result. This will allocate memory and give you an array with your 
results. Otherwise, no allocation at all. That result array can 
be const, if you want. If you need to access your elements only 
once, there's no need to have an array.

I really don't see what's not working in this.

And by the way, there's no need to put const on everything. An 
optimizing compiler is often able to infer things, especially for 
stack allocated local variables.


More information about the Digitalmars-d-learn mailing list