Hi! What do folks think about adding
impl Vec<T> {
fn sorted(self) -> Vec<T> where T: Ord {
let mut this = self;
this.sort();
this
}
// and seven other `sort` flavors?
}
to the stdlib?
This method would allow to replace
let mut deps_metadata = cx.dep_targets(unit)
.iter()
.map(|dep| metadata_of(dep, cx, metas))
.collect::<Vec<_>>();
deps_metadata.sort();
with a more fluent version:
let deps_metadata = cx.dep_targets(unit)
.iter()
.map(|dep| metadata_of(dep, cx, metas))
.collect::<Vec<_>>()
.sorted();
While seemingly a trivial change, I think it is a nice readability improvement over “collect to a mut vec, then sort”. The problem with the latter approach is that you have to declare the variable as mut
, and so all future readers would wonder “is this mut only for sorting, or do we genuinely push and pop something down the line?”. Also in some cases it should be possible to get rid of the variable altogether.
At least in my experience, in the majority of case sorted
is a more natural API then sort
. To test this hypothesis, I’ve tired to change Cargo to use sorted
. There were 20 call altogether, and in 15 cases it was possible to take advantage of sorted
: https://github.com/matklad/cargo/commit/3ff7ccc82dc9b555c25e7df97e1afde648810399
The proposal is not without drawbacks, naturally! We already have a large variety of sorting methods, and this proposal further doubles their quantity! What’s more, while sort
is implemented for &mut [T]
, sorted necessary has to be implemented for Vec<T>
.