questions around mutating range algorithms, const, and return ref

aliak something at something.com
Mon Jan 29 11:36:26 UTC 2018


On Monday, 29 January 2018 at 06:46:26 UTC, Ali Çehreli wrote:
> I think the following trivial wrapper around 
> std.algorithm.remove() should do:
>
> void removeMatching(R, N)(ref R r, N needles) {
>     import std.algorithm : remove, canFind;
>     r = r.remove!(e => needles.canFind(e));
> }
>

Haha awesome! Yes that's much better :)

Note to self: learn to scroll down in the docs to find other 
definitions. I was convinced that remove only acted on indices :p

> I'm not convinced that unfoundElements is needed at all. :)

Can't argue with that :)

> > 6) It will not work when I pass in a range that has const
> elements.
> >
> > ie:
> >
> > const(int)[] arr = [1, 2, 3, 4, 5];
> > arr.pull([2, 3]);
> >
> > This I guess makes sense because moveEmplaceAll depends on
> isInputRange
> > and from my understanding, a const range cannot be one (is
> that
> > correct?).
>
> Yes but your range is not const, the elements are. So, although 
> const(int)[] is a range, it does not have mutable elements.

Ah right, yes the range is not const indeed.

> You don't want to mutate const elements anyway. It would be 
> breaking a promise that other parts of the program may be 
> depending on. I would return a filtered-out range:

Right, I want to mutate the range though, not the elements. So 
moving things from one location is not considered as a const 
violation in c++ for eg, maybe the D way is different though? Any 
reading material there?

Also hasMobileElements!(const int[]) is true, so that means I can 
move elements around right?

If I can move elements, that means I should be able to move the 
ones I want to the beginning, of the range, but then I'm also 
unsure about how to go about changing the size of a range.

popBack on a mutable range with const data might cause 
destructors to be called, so I'm going to say that should be ok 
because as a user, if you're calling a range that mutates by 
removing things, and if you try and access those things later 
that's probably along the same lines as removing elements from a 
range that you're "foreach"ing over.

And your second approach is definitely more practical I'd say, 
but I'm going to go about this as a learning exercise in dealing 
with mutations, and const with ranges in D.

Thanks you for the comments!




More information about the Digitalmars-d-learn mailing list