Proposal: takeFront and takeBack

Jonathan M Davis jmdavisProg at gmx.com
Thu Jul 5 17:40:01 PDT 2012


On Thursday, July 05, 2012 23:59:47 David Piepgrass wrote:
> (grain of salt, I'm new to D.)
> 
> I'd vote for consumeFront being always available, because it's
> distinctly more convenient to call one function instead of two,
> especially when you expect that making a copy of front is cheap
> (e.g. a collection of pointers, numbers or slices). Ranges where
> 'front' returns a pointer to a buffer that popFront destroys
> (overwrites) are surely in the minority, right? So I hope they
> would be retrofitted to support consumeFront.
> 
> But, given that popFront is allowed to be destructive to the
> value of front, by re-using the same buffer (and that the
> proposed consumeFront might also be implemented with 'delayed
> destruction' to front), I am wondering how one is supposed to
> implement generic code correctly when this is unacceptable, e.g.:
> 
> void append(Range1,Range2)(Range1 input, ref Range2 output)
> {
> 	// Usually works, unless input.popFront happens to be
> destructive?
> 	foreach(e; input) output ~= e;
> }

That's generally just fine. The only ranges in Phobos which would have any 
problem with that would be the ones in std.stdio which reuse a buffer for 
front, and I wouldn't really expect other ranges to have that sort of problem 
unless they were doing the same thing. It mostly becomes an issue of knowing 
which ranges you have to be careful of that way, and being careful what you 
pass them to. So, I wouldn't worry about it all that much in general, but 
something like consumeFront would break them entirely, since if it were 
introduced, then presumably, it would be used fairly heavily by many range-
based functions, and it's guaranteed not to work with them, whereas a 
situation like your code above would be fairly rare, and it would generally be 
clear to the user of a range like ByLine that the function that they're 
passing it to would be doing something like appending each element in it into 
a new range, which wouldn't work, so they'd take precautions, like wrapping it 
in a call to map which duped the elements before passing it to append.

- Jonathan M Davis


More information about the Digitalmars-d mailing list