tazjin / nix-1p

A (more or less) one page introduction to Nix, the language.
https://code.tvl.fyi/about/nix/nix-1p
896 stars 24 forks source link

Confusing example for formals defaulting #11

Closed boozedog closed 1 year ago

boozedog commented 1 year ago

Reading this section: https://github.com/tazjin/nix-1p#multiple-arguments-attribute-sets

I ran across this snippet:

({ a ? 1, b }@args: args.a) { b = 1; }

I'm wondering what the parenthesis are used for in this case. it almost looks like shorthand for let ... in but I don't see this syntax described elsewhere in this document?

tazjin commented 1 year ago

In this snippet, we define a function { a ? 1, b }@args: args.a, that is a function which receives an attribute set with the key b and optionally a (with a defaulting to 1 if it is not supplied), and which binds this attribute set to the name args and returns args.a.

This function is then called with the parameter { b = 1; }, in which there is no key a, and with a defaulting to 1 it will now return 1.

The parenthesis are needed here because the Nix parser gets tripped up on the distinction between the function definition and the function otherwise. It would think that args.a { b = 1; } is a function call.