`Vec::rdedup(_by(_key))`?

Vec::dedup related methods "removes all but the first of consecutive elements in the vector". Is there a need for a method removes all but the last equal items?

What is the use case?

1 Like

I have a sorted Vec like [(1, 3), (1, 4), (2, 3)], each item is a (price, value) pair. I want to know for all things of the same price, how much value can I get.

A reasonable thought is v.dedup_by_key(|current, previous| current.0 == previous.0 && current.1 >= previous.1), but it will always remove the previous one according to the doc.

If rdedup_by_key is provided, the code above can be used, with dedup changed to rdedup.

I can call reverse -> dedup -> reverse to achieve the same result, but it would be so costly.

One alternative solution would be sorting them in reverse order.

It's probably worth while to check out some kind of DataFrame. I don't think it's worthwhile to add this specific table operation to Vec on its own, and if multiple such operations were to be added they might be better grouped by a different abstraction altogether.

Vec::dedup_by gives the closure &mut-access to both items, so you're free to modify the item that will be kept.

v.dedup_by(|next, prev| {
    next.0 == prev.0 && {
        std::mem::swap(next, prev);
        true
    }
})
6 Likes

The process for such proposals is to submit an ACP.

Oh I really like this idea