lib: optimize setAttrByPath and cleaup imports

- Remove inheritance of `lists.fold` as it isn't used anywhere.
- Inherit `foldl'` for consistency as only `cartesianProductOfSets` explicitly
  reference lib.
- Inline `foldr` to generate nested attrs instead of using `listToAttrs` and `tail`.
This commit is contained in:
polykernel 2021-08-20 12:24:39 -04:00
parent 6fb5d4cedc
commit 3f4ce46a47

View file

@ -5,7 +5,7 @@ let
inherit (builtins) head tail length; inherit (builtins) head tail length;
inherit (lib.trivial) and; inherit (lib.trivial) and;
inherit (lib.strings) concatStringsSep sanitizeDerivationName; inherit (lib.strings) concatStringsSep sanitizeDerivationName;
inherit (lib.lists) fold foldr concatMap concatLists; inherit (lib.lists) foldr foldl' concatMap concatLists elemAt;
in in
rec { rec {
@ -55,10 +55,13 @@ rec {
=> { a = { b = 3; }; } => { a = { b = 3; }; }
*/ */
setAttrByPath = attrPath: value: setAttrByPath = attrPath: value:
if attrPath == [] then value let
else listToAttrs len = length attrPath;
[ { name = head attrPath; value = setAttrByPath (tail attrPath) value; } ]; atDepth = n:
if n == len
then value
else { ${elemAt attrPath n} = atDepth (n + 1); };
in atDepth 0;
/* Like `attrByPath' without a default value. If it doesn't find the /* Like `attrByPath' without a default value. If it doesn't find the
path it will throw. path it will throw.
@ -195,7 +198,7 @@ rec {
] ]
*/ */
cartesianProductOfSets = attrsOfLists: cartesianProductOfSets = attrsOfLists:
lib.foldl' (listOfAttrs: attrName: foldl' (listOfAttrs: attrName:
concatMap (attrs: concatMap (attrs:
map (listValue: attrs // { ${attrName} = listValue; }) attrsOfLists.${attrName} map (listValue: attrs // { ${attrName} = listValue; }) attrsOfLists.${attrName}
) listOfAttrs ) listOfAttrs