DMD 0.177 release [Length in slice expressions]

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Wed Dec 20 15:04:33 PST 2006


Chris Nicholson-Sauls wrote:
> BCS wrote:
>> Chris Nicholson-Sauls wrote:
>>> The "[..$]" syntax is also present in ColdC and its relatives 
>>> (including my Bovis), so it was familiar to me from the beginning.  
>>> (That said I still harbor thoughts that $ could be used for other 
>>> things... but honestly, I think the syntax would be unambiguous: a 
>>> lone $ as the right hand side of a slice expression should easily 
>>> enough be distinguishable from a $ anywhere followed by something, 
>>> like an identifier.)
>>>
>>
>> FWIW $ is not only used for the RHS of a slice
>>
>> char[] str;
>> str[$/2..$];    // 2nd half of array
>> str[$-1];    // last element in array
>> str[$-5..$];    // last 5 things in array
>> str[$-10..10];    // um... well... you get the idea
> 
> Ack.  Having never used anything quite like that before, I guess I had 
> assumed the $ only had meaning as I described above.  Still, it could be 
> possible.

These are very possible and are at times very useful. Though the last 
example is perhaps pushing it in the latter department ;).
But yeah, $ is valid inside any [] pair, whether as (part of) an index 
or as (part of) either side of a slice.

>>> Which leads me to another thought.  One other operator that ColdC and 
>>> family posesses is the @ for list splicing.  Useless sample ColdC:
>>>
>>> # var foo, bar, result;
>>> #
>>> # foo = {1, 2, 3};
>>> # bar = {4, 5, 6};
>>> # result = {@foo, @bar};
>>>
>>> The 'result' variable now equals {1, 2, 3, 4, 5, 6}.
>>
>> I would think this would be the same thing.
>>
>> auto foo = [1,2,3];
>> auto bar = [4,5,6];
>> auto result = foo ~ bar;
>>
>> am I missing somethign?
> 
> Not really, no.  But consider:
> 
> # ColdC                          D
> #
> # result = {@foo, 0, @bar};      result = foo ~ [0] ~ bar;

You don't need to surround a non-array by [] if concatenating with an 
array of the same type:
                                    result = foo ~ 0 ~ bar;
will work just fine.

> # result = {42, @someFunc()};    result = [42] ~ someFunc();

                                    result = 42 ~ someFunc();

> # result = {@foo, 1, @foo, 2};   result = foo ~ [1] ~ foo ~ [2];

                                    result = foo ~ 1 ~ foo ~ 2;

> # result = {3, 6, @myConst, 9};  result = [3, 6] ~ myConst.dup ~ [9];

                                    result = [3, 6] ~ myConst ~ 9;

The first []s are still needed, unless you add parentheses to group the 
6 to myConst (and possibly the 9), but the last ones are unnecessary. 
Also, .dup is completely useless here (presuming myConst is an array) 
since ~ always allocates. (Note that repeated ~s in the same expression 
only allocate once though, at least in DMD)



More information about the Digitalmars-d-announce mailing list