Open
Description
Summary
Hello,
The standard library is laking a natural sort algorithm.
Here is a possible implementation :
proc naturalSort*(l: openArray[string]): seq[string] =
l.sorted(
proc(a, b: string): int =
var ai = 0
var bi = 0
while true:
if ai > high(a) or bi > high(b):
return a.len() - ai - b.len() + bi
if not (a[ai].isDigit() and b[bi].isDigit()):
let diff = cmp(a[ai], b[bi])
if diff != 0:
return diff
ai += 1; bi += 1
else:
var
aNum: int
bNum: int
ai += parseInt(a[ai .. ^1], aNum)
bi += parseInt(b[bi .. ^1], bNum)
let diff = cmp(aNum, bNum)
if diff != 0:
return diff
)
Thanks !
Description
Definition : In computing, natural sort order (or natural sorting) is the ordering of strings in alphabetical order, except that multi-digit numbers are treated atomically, i.e., as if they were a single character. Natural sort order has been promoted as being more human-friendly ("natural") than machine-oriented, pure alphabetical sort order.
It could be a nice addition, as it is can be quite common to use it for file versionning, reports, etc.
Alternatives
No response
Examples
No response
Backwards Compatibility
No response
Links
No response