Skip to content

Add list sort builtins using a new ordering API#9832

Draft
jrrrp wants to merge 4 commits into
roc-lang:mainfrom
jrrrp:sort-builtins
Draft

Add list sort builtins using a new ordering API#9832
jrrrp wants to merge 4 commits into
roc-lang:mainfrom
jrrrp:sort-builtins

Conversation

@jrrrp

@jrrrp jrrrp commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Following the discussion in Zulip^1 this PR

  • Converts LT/EQ/GT ordering tags to FirstBeforeSecond, Equivalent, SecondBeforeFirst to denote which of the two arguments in the comparison comes before the other. This decouples ordering from "less than" and by extension from the operators <, > etc.
  • When a default sort is desirable, modules can implement t.default_cmp : t, t -> [FirstBeforeSecond, Equivalent, SecondBeforeFirst]
  • Integers and tuples are two such primitives where it may make sense to have a default ordering, unlike strings.

Testing

  • Updated existing tests referencing List.sort_with

Todo

  • Remaining list builtins (sort_by, reverse) and snapshot tests. They will eventually be re-implemented in Zig but I figured it could be solidified in Roc first.

Before I finish I thought I'd check that the naming is still ok:

List.sort(list, comparison_func)
List.sort_with_default(list)
item.default_cmp(other) # Returns one of [FirstBeforeSecond, Equivalent, SecondBeforeFirst]
List.sort_by(list, mapper_fn)

# Reverse:
List.sort_rev(list, comparison_func)
List.sort_with_default_rev(list)
List.sort_by_rev(list, mapper_fn)

In particular, sort_with_default_rev is quite verbose, and if you want to define a comparison function inline, it looks like this:

expect [3, 1, 2].sort(|a, b| if a < b FirstBeforeSecond else if a > b SecondBeforeFirst else Equivalent) == [1, 2, 3]

[1] https://roc.zulipchat.com/#narrow/channel/304641-ideas/topic/Sorting.20tuples.3F/with/606333839
https://roc.zulipchat.com/#narrow/channel/304641-ideas/topic/List.20sort.20builtins/with/605016649

@jrrrp jrrrp force-pushed the sort-builtins branch 4 times, most recently from bb4d55e to e8d2bed Compare June 30, 2026 16:39
jrrrp added 4 commits June 30, 2026 19:24
This presumes that types by convention will implement a default_cmp method,
if it makes sense to have a default sort.

This could make sense for Integers, Tuples (lexicographic sort), and Dec.

Str for example will not, as there is no good default sort for strings that is
sensitive to different locales, or different string content (e.g., strings
containing numbers).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant