Skip to content

Commit

Permalink
Don't require T: Compare for Array.sort_by
Browse files Browse the repository at this point in the history
This isn't necessary as Array.sort_by takes a custom comparison closure.
This change in turn allows using Array.sort_by when the values don't
implement the Compare trait.

Changelog: fixed
  • Loading branch information
yorickpeterse committed Jan 21, 2024
1 parent db33be8 commit 6a985ad
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 25 deletions.
45 changes: 21 additions & 24 deletions std/src/std/array.inko
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,7 @@ let VALUE_SIZE = 8
# The capacity to use when resizing an array for the first time.
let START_CAPACITY = 4

fn stable_sort[T: Compare[T]](
array: mut Array[T],
compare: mut fn (ref T, ref T) -> Bool,
) {
fn stable_sort[T](array: mut Array[T], compare: mut fn (ref T, ref T) -> Bool) {
let len = array.size

# The algorithm here is the recursive merge sort algorithm. While faster
Expand All @@ -41,7 +38,7 @@ fn stable_sort[T: Compare[T]](
merge_sort(tmp, array, start: 0, end: len, compare: compare)
}

fn merge_sort[T: Compare[T]](
fn merge_sort[T](
a: mut Array[T],
b: mut Array[T],
start: Int,
Expand Down Expand Up @@ -562,6 +559,25 @@ class builtin Array[T] {
@size += 1
}

# Sorts the values in `self` using a custom comparison closure.
#
# Like `Array.sort`, this method performs a stable sort.
#
# # Examples
#
# let nums = [0, 3, 3, 5, 9, 1]
#
# nums.sort_by fn (a, b) { b.cmp(a) }
# nums # => [9, 5, 3, 3, 1, 0]
fn pub mut sort_by(block: fn (ref T, ref T) -> Ordering) {
stable_sort(self) fn (a, b) {
match block.call(a, b) {
case Less or Equal -> true
case _ -> false
}
}
}

fn to_pointer -> Pointer[T] {
@buffer as Pointer[T]
}
Expand Down Expand Up @@ -779,25 +795,6 @@ impl Array if T: Compare[T] {
fn pub mut sort {
stable_sort(self) fn (a, b) { a <= b }
}

# Sorts the values in `self` using a custom comparison closure.
#
# Like `Array.sort`, this method performs a stable sort.
#
# # Examples
#
# let nums = [0, 3, 3, 5, 9, 1]
#
# nums.sort_by fn (a, b) { b.cmp(a) }
# nums # => [9, 5, 3, 3, 1, 0]
fn pub mut sort_by(block: fn (ref T, ref T) -> Ordering) {
stable_sort(self) fn (a, b) {
match block.call(a, b) {
case Less or Equal -> true
case _ -> false
}
}
}
}

# An iterator that moves values out of an `Array`.
Expand Down
2 changes: 1 addition & 1 deletion std/test/std/test_array.inko
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ fn pub tests(t: mut Tests) {
)
}

t.test('Array.sort') fn (t) {
t.test('Array.sort_by') fn (t) {
let nums = [56, 20, 28, 71, 42, 49, 1, 59, 19, 18, 27, 6, 31, 89, 32]

nums.sort_by fn (a, b) { b.cmp(a) }
Expand Down

0 comments on commit 6a985ad

Please sign in to comment.