Proposal: takeFront and takeBack

Roman D. Boiko rb at d-coding.com
Tue Jul 3 10:49:28 PDT 2012


On Tuesday, 3 July 2012 at 17:40:24 UTC, Jonathan M Davis wrote:
> On Tuesday, July 03, 2012 17:31:21 Christophe Travert wrote:
>> takeFront implementation is dangerous for ranges which 
>> invalidates their
>> front value when popFront is called, for instance, 
>> File.byLine. Thus
>> takeFront will have to be used with care: any range implement 
>> takeFront
>> (because of the template and USFC), but it may not be valid. 
>> That makes
>> the range interface more complicated: There is a takeFront 
>> property, but
>> you have to check it is safe to use... how do you check that 
>> by the way?
>
> Hmm. I hadn't thought of that. That could be a good reason not 
> to do this. I'm
> not quite sure how to get around that. Hmmm... It would 
> arguably be a bit
> ugly, but a range which couldn't safely be used with takeFront 
> could have an
> enum on it which indicated that, and takeFront would fail to 
> compile if used
> with such a range. Of course, that would mean that you'd have 
> to special case
> such ranges in any range-based function which used takeFront so 
> that there was
> a branch which didn't use takeFront for ranges which couldn't 
> use it.

Just an idea (feels dirty, but still): such range could redefine 
takeFront, and maintain state. takeFront would defer a call to 
popFront until the next operation. All of front, popFront, 
takeFront and empty would check state (whether popFront has been 
deferred), and execute popFront first. Side effect would be that 
a call to empty would invalidate result of takeFront, but that 
could be changed also: empty instead of calling popFront would 
check whether there is anything else after the front element.

This is much more complicated, but would only be necessary for 
such containers.



More information about the Digitalmars-d mailing list