v icon indicating copy to clipboard operation
v copied to clipboard

arrays: sorting functions for immutable arrays

Open memoriesadrift opened this issue 1 year ago • 7 comments

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.

memoriesadrift avatar Mar 04 '23 20:03 memoriesadrift

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 avatar Mar 05 '23 13:03 JalonSolov

@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.

medvednikov avatar Mar 05 '23 14:03 medvednikov

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.

JalonSolov avatar Mar 05 '23 14:03 JalonSolov

arr.sorted(b > a) is going to work if this function is moved to arr.sorted()

medvednikov avatar Mar 05 '23 14:03 medvednikov

I'm in favour of moving it to builtins, will move it there.

memoriesadrift avatar Mar 05 '23 14:03 memoriesadrift

@memoriesadrift where do we stand here?

ylluminate avatar Apr 14 '23 01:04 ylluminate

@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.

memoriesadrift avatar Apr 17 '23 15:04 memoriesadrift

Closing, since .sorted() and .sorted_with_compare() were implemented in 58b6ba8 .

spytheman avatar Sep 01 '23 07:09 spytheman