diff options
author | volth <volth@webmaster.ms> | 2018-06-10 17:31:09 +0000 |
---|---|---|
committer | xeji <36407913+xeji@users.noreply.github.com> | 2018-06-10 19:31:09 +0200 |
commit | 4e85c4ff277c883edf67d87d5d7d158a49dc4850 (patch) | |
tree | 0edc48d8848518f61cd229e7029befc83b18f892 /lib/lists.nix | |
parent | 95a8cb3ade1ad0e2649f0f3128e90c53964af5e1 (diff) | |
download | nixpkgs-4e85c4ff277c883edf67d87d5d7d158a49dc4850.tar nixpkgs-4e85c4ff277c883edf67d87d5d7d158a49dc4850.tar.gz nixpkgs-4e85c4ff277c883edf67d87d5d7d158a49dc4850.tar.bz2 nixpkgs-4e85c4ff277c883edf67d87d5d7d158a49dc4850.tar.lz nixpkgs-4e85c4ff277c883edf67d87d5d7d158a49dc4850.tar.xz nixpkgs-4e85c4ff277c883edf67d87d5d7d158a49dc4850.tar.zst nixpkgs-4e85c4ff277c883edf67d87d5d7d158a49dc4850.zip |
lib: add groupBy (#38612)
Diffstat (limited to 'lib/lists.nix')
-rw-r--r-- | lib/lists.nix | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/lib/lists.nix b/lib/lists.nix index 5ec97f5a07f..194e1c200ec 100644 --- a/lib/lists.nix +++ b/lib/lists.nix @@ -250,6 +250,42 @@ rec { else { right = t.right; wrong = [h] ++ t.wrong; } ) { right = []; wrong = []; }); + /* Splits the elements of a list into many lists, using the return value of a predicate. + Predicate should return a string which becomes keys of attrset `groupBy' returns. + + `groupBy'' allows to customise the combining function and initial value + + Example: + groupBy (x: boolToString (x > 2)) [ 5 1 2 3 4 ] + => { true = [ 5 3 4 ]; false = [ 1 2 ]; } + groupBy (x: x.name) [ {name = "icewm"; script = "icewm &";} + {name = "xfce"; script = "xfce4-session &";} + {name = "icewm"; script = "icewmbg &";} + {name = "mate"; script = "gnome-session &";} + ] + => { icewm = [ { name = "icewm"; script = "icewm &"; } + { name = "icewm"; script = "icewmbg &"; } ]; + mate = [ { name = "mate"; script = "gnome-session &"; } ]; + xfce = [ { name = "xfce"; script = "xfce4-session &"; } ]; + } + + + groupBy' allows to customise the combining function and initial value + + Example: + groupBy' builtins.add 0 (x: boolToString (x > 2)) [ 5 1 2 3 4 ] + => { true = 12; false = 3; } + */ + groupBy' = op: nul: pred: lst: + foldl' (r: e: + let + key = pred e; + in + r // { ${key} = op (r.${key} or nul) e; } + ) {} lst; + + groupBy = groupBy' (sum: e: sum ++ [e]) []; + /* Merges two lists of the same size together. If the sizes aren't the same the merging stops at the shortest. How both lists are merged is defined by the first argument. |