git.iko.soy/typeable/nixpkgs
on master help sign in
Merge pull request #38611 from volth/nat-sort

lib: add naturalSort

commit0fe11dbeddb06e319483e16770646ba144a3e833 authorJörg Thalheim <Mic92@users.noreply.github.com> dateSun 8 Apr 2018, 22:44 (9 years ago) parent9f028023f8c910
2 files changed+23−2
lib/default.nix+1−1 lib/lists.nix+22−1
lib/default.nix+1−1
@@ -74,7 +74,7 @@ let
7474 inherit (lists) singleton foldr fold foldl foldl' imap0 imap1
7575 concatMap flatten remove findSingle findFirst any all count
7676 optional optionals toList range partition zipListsWith zipLists
77− reverseList listDfs toposort sort compareLists take drop sublist
77+ reverseList listDfs toposort sort naturalSort compareLists take drop sublist
7878 last init crossLists unique intersectLists subtractLists
7979 mutuallyExclusive;
8080 inherit (strings) concatStrings concatMapStrings concatImapStrings
lib/lists.nix+22−1
@@ -1,7 +1,9 @@
11# General list operations.
22{ lib }:
33with lib.trivial;
4−
4+let
5+ inherit (lib.strings) toInt;
6+in
57rec {
68
79 inherit (builtins) head tail length isList elemAt concatLists filter elem genList;
@@ -409,6 +411,25 @@ rec {
409411 then compareLists cmp (tail a) (tail b)
410412 else rel;
411413
414+ /* Sort list using "Natural sorting".
415+ Numeric portions of strings are sorted in numeric order.
416+
417+ Example:
418+ naturalSort ["disk11" "disk8" "disk100" "disk9"]
419+ => ["disk8" "disk9" "disk11" "disk100"]
420+ naturalSort ["10.46.133.149" "10.5.16.62" "10.54.16.25"]
421+ => ["10.5.16.62" "10.46.133.149" "10.54.16.25"]
422+ naturalSort ["v0.2" "v0.15" "v0.0.9"]
423+ => [ "v0.0.9" "v0.2" "v0.15" ]
424+ */
425+ naturalSort = lst:
426+ let
427+ vectorise = s: map (x: if isList x then toInt (head x) else x) (builtins.split "(0|[1-9][0-9]*)" s);
428+ prepared = map (x: [ (vectorise x) x ]) lst; # remember vectorised version for O(n) regex splits
429+ less = a: b: (compareLists compare (head a) (head b)) < 0;
430+ in
431+ map (x: elemAt x 1) (sort less prepared);
432+
412433 /* Return the first (at most) N elements of a list.
413434
414435 Example: