Sort tuple

Any reason this shouldn’t work?

julia> sort((1,2,3))
ERROR: MethodError: no method matching sort(::Tuple{Int64, Int64, Int64})

Sorting usually requires to swap elements in the process. That is generally more efficient in Vectors, even though it maybe can be optimized for small number of elements.

You can use

using StaticArrays
x = @SVector rand(10)  # or SVector( (1,2,3) )
x = sort(x)
1 Like

See also GitHub - tkf/Baselet.jl: Base API optimized for tuples

4 Likes

Linking related Github thread.

2 Likes

This package can sort a tuple.

Sorting Tuples was added to Julia once, but then removed before it was actually released: Support sorting iterators by LilithHafner · Pull Request #46104 · JuliaLang/julia · GitHub. Maybe that PR could be revived in a more limited form?

1 Like

TupleTools.jl has a sort method.

1 Like

that was a bit different.
That was sorting any iterable via making sort fall back to sort(collect(iter))
which will return a Vector.
and it was removed after decided that it was undesirable for an operation like sort to just generically return a different type to what it got as input.

idk if for tuples if sort on a tuple would make sense to return a Vector or not.
I lean towards not, and that one should either call collect yourself if you want that.
or use a sorting network if you don’t

I think having sort on tuples returning a tuple makes sense. It was unfortunate that that feature got bundled up in Support sorting iterators by LilithHafner · Pull Request #46104 · JuliaLang/julia · GitHub which was really about something completely different so it ended up getting reverted along with the rest.

1 Like

I agree.

For NTuples, that PR returned NTuple and was quite performant.