Idiomatic way to process const/immutable arrays as ranges
Steven Schveighoffer
schveiguy at yahoo.com
Mon Feb 11 09:25:53 PST 2013
On Mon, 11 Feb 2013 12:01:53 -0500, Dicebot <m.strashun at gmail.com> wrote:
> On Monday, 11 February 2013 at 16:35:22 UTC, Steven Schveighoffer wrote:
>> in means "const scope". scope is a no-op, const makes the array const,
>> including the pointer length.
>>
>> const(T)[] means, the ELEMENTS are const, but the pointer and length
>> can be changed. This makes it a valid input range.
>>
>> Since your function is making a copy of the data, this should be fine.
>>
>> Your explanation is difficult to understand, I'm basically going on
>> what your code does. If you change "in string[]" to "const(string)[]",
>> the function should compile.
>
> I know all of this. And I need guarantees that initial slice will always
> start at the very same point and will never be consumed by any part of
> this function. Thus, I do not need tail const and in is exactly what I
> want. But I see no reason why I can't copy slice pointers to create a
> new tail const range to consume.
>
> To sum up: I want to maintain full const for parameter range/slice but
> be able to create a tail const range from it every time I want to
> actually consume it. Without copying data itself.
Ah, ok. So that isn't the complete function.
The answer is, yes you can make a tail const variable from a const
variable:
string func(in string[] args)
{
const(string)[] tmpargs = args;
return tmpargs.join(" ");
}
Hm... trying this out, it doesn't work. The assignment to tmpargs works
alright, it's the join call that doesn't. Even my original suggestion
doesn't work. The problem is that const(string) is not an input range.
join requires each element from its input range to also be an input
range. But of course, const(string) (which is not an input range)
implicitly casts to string (which is an input range). So join simply
isn't taking that step.
We seriously need to fix this kind of problem. I think someone had
proposed at some point that tail-const/tail-immutable versions are always
preferred in all cases, but I guess that never went through.
Maybe there are other ways to fix this.
-Steve
More information about the Digitalmars-d-learn
mailing list