Is there something like a consuming take?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Jul 7 09:01:53 UTC 2019


On Saturday, July 6, 2019 11:02:15 PM MDT berni via Digitalmars-d-learn 
wrote:
> Or better: I'd like to hand in my voucher and get back two
> vouchers, one for the first 5 bytes and one for the rest. That's
> actually, what I thought, take() is doing...

Without slicing, that's impossible without iterating over the elements
multiple times. It would be possible to have a function like take that did
something like return a tuple of two ranges where the first one is the taken
elements, and the second one is the rest, but without slicing, that could
only be done by calling save so that the two ranges are independent copies
of the original range, and then the range that doesn't have the elements
that were taken off has to internally pop off all of the elements that were
taken so that its first element is the first one that wasn't taken. There's
no way to magically skip the taken elements for the second range without
slicing.

The alternative is to manually iterate through all of the elements that you
want to take, doing whatever you're going to do with them, and then doing
whatever you want to do with rest of the range after that. Then iteration
only occurs once. But that means that you don't have a range of the taken
elements and can't do something like pass them to another algorithm as a
range without constructing a new range from them, and if you're going to do
that, you might as well just call save, pass the range to take, and the call
drop on the original range to pop off the elements that were taken.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list