Search code examples
nixnixos

AttributeSet expression in Nix Expression


If the following nix expression

let
  f = "f";
  o = "o";
  b = "b";
  func = {a ? f, b ? "a" , c ? ""}: a+b+c; #only modify this line!
in
rec {
  foo = func {b="o"; c=o;}; #must evaluate to "foo"
  bar = func {a=b; c="r";}; #must evaluate to "bar"
  foobar = func {a=foo;b=bar;}; #must evaluate to "foobar"
}
  1. Here {a ? f, b ? "a" , c ? ""}: a+b+c; we are declaring that a function takes attribute set {a ? f, b ? "a" , c ? ""} as argument.
  2. Here func {b="o"; c=o;} we are passing an attribute set({b="o"; c=o;})to the function.

In the first expression we have "," separating the keys of attribute set and in the second "," is separating the keys. To represent attribute set we use two different methods. Is this understanding correct.?


Solution

  • The syntax { param ? default }: x defines an anonymous function that takes an attribute set with optional attribute param.

    in the second "," is separating the keys.

    In an attribute set, you use ; as a separator. I think this is a typo because your example is correct.

    You can read more about "set patterns" in function definitions in the Nix manual.

    Your understanding seems to be correct.