Skip to content

Support comparison functions in array.sorted - #5627

Merged
laurmaedje merged 15 commits into
typst:mainfrom
MDLC01:array-sorted-by
Apr 2, 2025
Merged

laurmaedje merged 15 commits into
typst:mainfrom
MDLC01:array-sorted-by

Conversation

@MDLC01

@MDLC01 MDLC01 commented Dec 25, 2024 •

Copy link
Copy Markdown
Collaborator

Closes #5365.

This PR is based on a rebased version of #5371 by @bluebear94. I used glidesort instead of the standard library sorting algorithm to prevent panics, which was the blocker for merging #5371.

Original post below.


This PR is based on a rebased version of #5371 by @bluebear94. As suggested in #5371 (comment), I implemented a custom sorting function that does not panic, which was the blocker for merging #5371.

Sorting algorithm

The sorting algorithm I implemented is an in-place stable insertion sort. In particular, it does not allocate anything. The drawback is that it is considerably slower than Rust's default sorting algorithm. I initially tried to implement an in-place stable merge sort,1 but was unable to reach a point where I was confident about my implementation.

Performance

I did a very basic benchmark that involved executing the following function:

#let test(len) = {
  let k = 0b01010101
  for m in range(256) {
    range(len).map(i => i.bit-xor(k).bit-and(m)).sorted()
  }
}

The total execution times of the for loop on my machine, as determined by --timings, are shown in the table below.

len 0.12.0 This PR
1000 2.11 s 3.10 s
10000 15.0 s 114 s

The difference seems quite significant for big arrays. The three solutions I can think of are:

  1. Deciding not to care (at the cost of performance).
  2. Only using the homemade sorting algorithm when a comparison function is provided (at the cost of performance when a comparison function is provided).
  3. Using a better sorting algorithm, such as an in-place stable merge sort (which may be harder to implement in a way that we can be confident is correct).
  4. Relying on a crate such as glidesort (at the cost of adding a new dependency).

I tend to think option 2. is better.

Footnotes

  1. https://thomas.baudel.name/Visualisation/VisuTri/inplacestablesort.html ↩

@xkevio

xkevio commented Dec 25, 2024 •

Copy link
Copy Markdown
Contributor

Could also use the glidesort crate instead of re-implementing a way worse sort to keep performance in all cases, mayhaps. This is what driftsort, the new Rust sorting algorithm, is based on but without the panicking total order check.

@MDLC01

MDLC01 commented Dec 26, 2024

Copy link
Copy Markdown
Collaborator Author

Yes we can also do that, but this requires adding a new dependency.

@laurmaedje

Copy link
Copy Markdown
Member

[...] but without the panicking total order check.

Is that stated somewhere? I couldn't find anything.

@xkevio

xkevio commented Jan 6, 2025 •

Copy link
Copy Markdown
Contributor

[...] but without the panicking total order check.

Is that stated somewhere? I couldn't find anything.

Not explicitly, but you can search for panic! or total order violation in the source code and you will find nothing.

@laurmaedje

Copy link
Copy Markdown
Member

I think I would prefer glidesort over an O(n^2) sort, even if it's an additional dependency.

@laurmaedje

Copy link
Copy Markdown
Member

I think key and compare wouldn't even need to be mutually exclusive. If there's a key, we could just compare the keys with the comparison function. What do you think?

@laurmaedje

Copy link
Copy Markdown
Member

From a quick look, looks like that's what the code actually does. Then, just the docs need an update.

@MDLC01

MDLC01 commented Jan 12, 2025

Copy link
Copy Markdown
Collaborator Author

I updated the documentation. There was already a test for the behavior.

@laurmaedje laurmaedje left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any thoughts on using by instead of compare as the name?

@MDLC01

MDLC01 commented Jan 23, 2025

Copy link
Copy Markdown
Collaborator Author

Quoting the original post from #5371:

I used compare for the argument name instead of by because by could plausibly refer to either the key or the comparison function.

Of course, I can change it to by if you prefer.

@laurmaedje

Copy link
Copy Markdown
Member

I don't know, I like how by reads and never found it confusing in Rust.

@MDLC01

MDLC01 commented Jan 23, 2025

Copy link
Copy Markdown
Collaborator Author

I'll change it in an hour or so

@MDLC01

MDLC01 commented Jan 23, 2025

Copy link
Copy Markdown
Collaborator Author

Should we allow by to return a float as well?

@laurmaedje

Copy link
Copy Markdown
Member

hmm, when sorting floats it might be useful, but the details around +/- 0 are a bit tricky. if we do, we should first investigate what other languages do.

@MDLC01

MDLC01 commented Jan 23, 2025

Copy link
Copy Markdown
Collaborator Author

In JavaScript, -0.0 === 0.0 (and -0.0 is the valid syntax for creating negative zero). I'm not aware of any other language that allows returning floats from comparison functions (notably, Lua expects a boolean, and Python doesn't even have this feature).

@xkevio

xkevio commented Jan 23, 2025

Copy link
Copy Markdown
Contributor

I feel like JavaScript is the last place one should look for inspiration in this regard. Personally, just returning integers with the clear {-1, 0, 1} seems sufficient to me.

@laurmaedje

Copy link
Copy Markdown
Member

The Lua case is interesting. To make a stable sort possible with just two return values I guess they need to ensure that the the first element passed to the comparison function is always the leftmost one. But if that is a guarantee that one can give, a boolean seems quite straightforward.

@MDLC01

MDLC01 commented Jan 23, 2025

Copy link
Copy Markdown
Collaborator Author

But if that is a guarantee that one can give, a boolean seems quite straightforward.

I don't think we can safely assume that if we stick with glidesort. At the same time, I agree that returning a boolean seems more user-friendly.

@laurmaedje

Copy link
Copy Markdown
Member

I think booleans would be much more convenient than -1, 0, 1, so I'd prefer to investigate a bit more whether that's somehow possible before proceeding.

@bluebear94

Copy link
Copy Markdown
Contributor

We can always convert from booleans to orderings using (b < a) - (a < b), but that requires two calls to the comparison function, so I don’t think that’s a good idea.

@laurmaedje laurmaedje added the waiting-on-design This PR or issue is blocked by design work. label Feb 25, 2025
@MDLC01

MDLC01 commented Feb 28, 2025

Copy link
Copy Markdown
Collaborator Author

I found a way to rely on glidesort while using a boolean comparison function, without calling it twice for each comparison.

The idea is that when a sorting algorithm calls a comparison function, there are only two possible outcomes: the elements are swapped, or they are not. This means out of the three outcomes (<, = or >), two (in practice, either < and =, or = and >) yield the same result. Essentially, for each comparison, the sorting algorithm only cares about either <= or >=. If we know which one for each comparison, we can just decide to pass the two arguments to by in whatever order gives us the desired result (as by computes <=, and therefore swapping its arguments computes >=). This is explained more formally in the code.

The drawback is that we need to make an extra allocation. This could be prevented when by is not passed, but would likely require duplicating some code. I think it's fine that way (glidesort allocates either way).

Additionally, I believe this method effectively makes any sorting algorithm stable. So maybe we can find even better sorting algorithms if we also include unstable sorting algorithms.

@laurmaedje laurmaedje removed the waiting-on-design This PR or issue is blocked by design work. label Mar 3, 2025
@laurmaedje laurmaedje added interface PRs that add to or change Typst's user-facing interface as opposed to internals or docs changes. scripting About Typst's coding capabilities labels Mar 24, 2025

@laurmaedje laurmaedje left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If key or by are specified, then Typst's function call overhead will most likely dominate the allocation cost anyway. But if neither is specified, I think we could skip all the complexity and have a separate code path for that. What do you think?

@MDLC01

MDLC01 commented Mar 31, 2025

Copy link
Copy Markdown
Collaborator Author

I initially did not do that because I feared it would have made the code even more complex. In the end, it's fine, but I'm not sure the performance impact is very noticeable. I may try to do a benchmark later if I have the time, but don't count on it.

@laurmaedje
laurmaedje added this pull request to the merge queue Apr 2, 2025
@laurmaedje

Copy link
Copy Markdown
Member

Thank you!

Merged via the queue into typst:main with commit 417f584 Apr 2, 2025
@MDLC01
MDLC01 deleted the array-sorted-by branch April 2, 2025 11:39
hongjr03 pushed a commit to hongjr03/typst that referenced this pull request Apr 16, 2025
Co-authored-by: +merlan #flirora <[email protected]>
Co-authored-by: Laurenz <[email protected]>
@Trebor-Huang Trebor-Huang mentioned this pull request May 16, 2025
1 task done
Dikluwe pushed a commit to Dikluwe/typst-crystalline that referenced this pull request Sep 12, 2026
Co-authored-by: +merlan #flirora <[email protected]>
Co-authored-by: Laurenz <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

interface PRs that add to or change Typst's user-facing interface as opposed to internals or docs changes. scripting About Typst's coding capabilities

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add compare argument to array.sorted, as an alternative to key

4 participants