query
On this page

mapAttrs

lib.mapAttrs

Primop
Docs pulled from | This Revision | about 1 hour ago


Nixpkgs manual

Apply a function to each element in an attribute set, creating a new attribute set.

Inputs

f

A function that takes an attribute name and its value, and returns the new value for the attribute.

attrset

The attribute set to iterate through.

Type

mapAttrs :: (String -> a -> b) -> { [String] :: a } -> { [String] :: b }

Examples

lib.attrsets.mapAttrs usage example

mapAttrs (name: value: name + "-" + value)
   { x = "foo"; y = "bar"; }
=> { x = "x-foo"; y = "y-bar"; }
(lib.attrsets.mapAttrs)

Nix manual

Takes 2 arguments

f, attrset

Apply function f to every element of attrset. For example,

builtins.mapAttrs (name: value: value * 10) { a = 1; b = 2; }

evaluates to { a = 10; b = 20; }.

Time Complexity

O(n) where:

n = number of attributes

Calls to f are performed afterwards, when needed.

Noogle detected

Aliases

Implementation

This function is implemented in c++ and is part of the native nix runtime.

src/libexpr/primops.cc:3573

static void prim_mapAttrs(EvalState & state, const PosIdx pos, Value ** args, Value & v)
{
    state.forceAttrs(*args[1], pos, "while evaluating the second argument passed to builtins.mapAttrs");

    auto attrs = state.buildBindings(args[1]->attrs()->size());

    for (auto & i : *args[1]->attrs()) {
        Value * vName = Value::toPtr(state.symbols[i.name]);
        Value * vFun2 = state.allocValue();
        vFun2->mkApp(args[0], vName);
        attrs.alloc(i.name).mkApp(vFun2, i.value);
    }

    v.mkAttrs(attrs.alreadySorted());
}