Search code examples
functional-programmingnix

Nix add variadic args to a set from a function


Is something like this possible in nix?

f = {x, y, ...}:
{
    x = x + 1;
    y = y + 2;
    ...;
}

where calling f on a set of arguments returns a set:

f { x = 1; y = 2; }                   -> { x = 2; y = 4; }
f { x = 1; y = 2; z = 5 }             -> { x = 2; y = 4; z = 5; }
f { x = 1; y = 2; z = 5; s = "str"; } -> { x = 2; y = 4; z = 5; s = "str"; }

To be clear. The set of ellipsis ... is the variadic argument type and does not mean etcetera used in everyday language. The solution here is to call get { ... } on ellipsis if possible. But I don't know if the language supports this.


Solution

  • This should work:

    f = args@{x, y, ...}: args // { x = x + 2; y = y + 2; }
    

    You can read more about it here:

    https://nixos.org/nix/manual/#ss-functions