On Monday, July 16, 2012 09:07:06 Jacob Carlborg wrote: > On 2012-07-16 00:03, Jonathan M Davis wrote: > > Iterators have exactly the same problem for exactly the same reasons as > > std.algorithm.remove (e.g. take a look at C++'s erase function). The only > > way to do this in place would be to create a separate removeInPlace > > function specifically for arrays. But since all it takes is reassigning > > the result of std.algorithm.remove to the array that you passed in and an > > std.array.replaceInPlace would be doing exactly that, I don't think that > > > > adding such a function buys us much: > > auto arr = [10, 22, 19, 4, 6]; > > arr = remove(arr, 3); > > assert(arr == [10, 22, 19, 6]); > > > > The main problem is understanding why remove (or erase in C++) works this > > way, which seems to throw off a bunch of people in both D and C++, but > > it's something that we're pretty much stuck with. You need the actual > > container (not an iterator or range) if you want to actually remove the > > element. > It would be really useful if std.algorithm (and similar functions) would > indicate clearly if they operate in place or not. It took me a while to > understand that "sort" operates in place. In Ruby this is achieved by a > naming convention: > > a = [3, 4, 5] > a = a.sort # returns a new array > a.sort! # sorts in place
We do have InPlace in function names when one version of a function operates in place and another doesn't, but we haven't generally done that on functions which only have one version, and I don't expect that to change now (at least not for existing functions). In any case, _most_ range-based functions _don't_ operate in place, but it's certainly true that the ones that do should make that clear in their documentation. remove is a bit of a special case, however, in that it does the changes in place but doesn't take a ref, so while the return value is shortened to not include the removed elements, the original is just as long as it was before (which is useful in cases where you want to then set the elements at the end), and you end up with something that's sort of in place and sort of not. Regardless, remove is confusing enough to most people (just like erase in C++) that it's documentation needs to be very clear, but I don't know how good it is or isn't. Given the difficulty of explaining it properly and Merhdad's confusion, it probably stands to be improved. - Jonathan M Davis