How to sort tuples? For example:
type
Person = tuple[name: string, age: int]
How to sort the persons by age?
Thank you in advance.
http://blaxpirit.com/blog/9/sort-by-min-by-max-by-in-nim.html
persons.sort((a, b) => cmp(a.age, b.age))
import algorithm
type
Person = tuple[name: string, age: int]
var
p1: Person = (name: "p1", age: 60)
p2: Person = (name: "p2", age: 20)
p3: Person = (name: "p3", age: 30)
p4: Person = (name: "p4", age: 30)
people1 = @[p1,p2,p4,p3]
people2 = @[p1,p2,p4,p3]
echo "Unsorted: : ",people1
### Do notation
people1.sort do (x, y: Person) -> int:
result = cmp(x.age, y.age)
if result == 0:
result = cmp(x.name, y.name)
### Anonymous proc
people2.sort(proc (x,y: Person): int =
result = cmp(x.age, y.age)
if result == 0:
result = cmp(x.name, y.name)
)
echo "Do notation : ", people1
echo "Anonymous proc: ", people2
I wonder which one is preferable? According to docs the "Do notation" will be removed at some point.
Or if you're on the devel branch:
echo persons.sortByIt(it.age)
The example @kuba gave does also sort on name if the age matches. Which is currently not possible with the new sortByIt(it.age, it.name) template.
So I thought this may be extended at least to support a nesting depth of two and three (after I failed to make it totally dynamic).
See this PR proposal: https://github.com/Araq/Nim/pull/2313
Google brought me here, so I'll point out that sortByIt was renamed to sortedByIt:
https://github.com/nim-lang/Nim/pull/2318/commits/06ea53e6920c561eb3ad27bfcbd57aba608b1bac
can sortedbyit support optional "reversed" arguement?
currently, if I only knew the 2-steps method:
var people3 =people1.sortedByIt(it.name)
var people4 = people3.reversed()
echo people4
I don't konw whether the above implementation is high effiency. what if an inner way like this
var people4 =people1.sortedByIt(it.name, True)
echo people4