Questions about the slice operator

Simen Kjærås simen.kjaras at gmail.com
Wed Apr 4 07:40:11 PDT 2012


On Wed, 04 Apr 2012 15:29:58 +0200, Jacob Carlborg <doob at me.com> wrote:

> On 2012-04-04 15:01, Simen Kjærås wrote:
>
>> Actually, I've thought a little about this. And apart from the tiny
>> idiosyncrasy of $, a..b as a more regular type can bring some
>> interesting enhancements to the language.
>>
>> Consider a..b as simply a set of indices, defined by a start point and
>> an end point. A different index set may be [1,2,4,5], or Strided!(3,4).
>>
>> An index set then works as a filter on a range, returning only those
>> elements whose indices are in the set.
>>
>> We can now redefine opIndex to take either a single index or an index
>> set, as follows:
>>
>> auto opIndex(S)(S set) if (isIndexSet!S) {
>> return set.transform(this);
>> }
>>
>> For an AA, there would be another constraint that the type of elements
>> of the index set match those of the AA keys, of course. Other containers
>> may have other constraints.
>>
>> An index set may or may not be iterable, but it should always supply
>> functionality to check if an index is contained in it.
>>
>> With this framework laid out, we can define these operations on arrays,
>> and have any array be sliceable by an array of integral elements:
>>
>> assert(['a','b','c'][[0,2]] == ['a', 'c']);
>
> I don't think I really understand this idea of an index set.
>

It's quite simple, really - an index set holds indices. For a regular
array of N elements, the index set it [0..N-1]. For an AA, the index set
is all the keys in the AA. Basically, an index set is the set of all
values that will give meaningful results from container[index].

arr[2..4] thus means 'restrict the indices to those between 2 and 4'.
For arrays though, it also translates the array so that what was 2
before, now is 0.

For a T[string] aa, one could imagine the operation aa["a".."c"] to
produce a new AA with only those elements whose keys satisfy
"a" <= key < "c".

As for the example given:

assert(['a','b','c'][[0,2]] == ['a', 'c']);

This means 'grab the elements at position 0 and 2, and put them in
a new array'. Hence, element 0 ('a') and element 2 ('c') are in
the result.


More information about the Digitalmars-d-learn mailing list