v
v copied to clipboard
arrays: sorting functions for immutable arrays
Since V arrays are immutable by default, sorting these arrays is unnecessarily obtuse, since sort() requires a mut array. Additionally, added an analogous function for sort_with_compare().
Use case such as this: Before
dims.map(fn (p []int) {
mut sorted := p.clone()
sorted.sort()
// do something with sorted array
})
After
import arrays
dims.map(fn (p []int) {
sorted := arrays.sorted(p)
// do something with sorted array
})
Note: There seems to be a bug with how &int parameter functions are passed as HOFs, thus trying to use arrays.sorted_with_compare() on []int will not compile.
Are we sure this is a good addition to vlib? It is "syntax sugar" for something that is only 2 lines in V now, and it is hard-coded for a single sorting case (a < b), instead of allowing for the full range of sorting options.
@JalonSolov it's not going to be hardcoded:
arr.sorted(a < b)
Returning an immutable sorted array is a frequently used feature, and is a must have in a language with immutability.
It is hard-coded in the source here. What if I want arr.sorted(b > a) instead? I'll still have to do the 2 lines in my code.
arr.sorted(b > a) is going to work if this function is moved to arr.sorted()
I'm in favour of moving it to builtins, will move it there.
@memoriesadrift where do we stand here?
@ylluminate Battled with adding it to builtin, but it's above my abilities, I'm not a compiler dev and am not very knowledgable in that area. The code in this PR works, though runs into the bug described in #17508.
Closing, since .sorted() and .sorted_with_compare() were implemented in 58b6ba8 .