diff --git a/lib/sort.dx b/lib/sort.dx index 1178dd0cc..3e4c6b561 100644 --- a/lib/sort.dx +++ b/lib/sort.dx @@ -63,6 +63,11 @@ def sort(xs: n=>a) -> n=>a given (n|Ix, a|Ord) = AsList(_, r) = reduce mempty mcombine xlists unsafe_cast_table(to=n, r) +def arg_sort(xs: n=>a) -> n=>n given (n|Ix|Ord, a|Ord) = + indexed_table = for i. (xs[i], i) + sorted = sort indexed_table + map snd sorted + def (+|)(i:n, delta:Nat) -> n given (n|Ix) = i' = ordinal i + delta from_ordinal $ select (i' >= size n) (size n -| 1) i' diff --git a/tests/sort-tests.dx b/tests/sort-tests.dx index 461a1b613..2bfc4422e 100644 --- a/tests/sort-tests.dx +++ b/tests/sort-tests.dx @@ -54,3 +54,9 @@ import sort :p is_sorted $ sort ["Charlie", "Alice", "Bob", "Aaron"] > True + +'### Test argsort +xs = ['1', '2', '3', '4', '9', '8', '7', '6'] +ixs = arg_sort xs +sort xs == for i. xs[ixs[i]] +> True