Nix (language): Difference between revisions

imported>Malteneuss
m Improve Strings, Lists and Sets examples
imported>Malteneuss
m Improve function explanation
Line 85: Line 85:
=== Functions ===
=== Functions ===


Functions have the following form: <code>pattern: body</code>
Functions are all unnamed (=lambda) functions with the following notation: <code>argument: nixExpression</code>, e.g. <code>x: x*x</code>.


There are 3 patterns in how functions can be written:
If you want to give that function a name, you have to assign it to a name, e.g. <code>square = x: x*x</code>.
So, <code>f(x) = x*x</code> in math is <code>f = x: x*x</code> in Nix.


# <code>f = a: a*a;</code> a single identifier, can be extended with multiple identifiers as <code>f = a: b: a*b;</code> as a partial function would be returned.
If you want to use that function and apply it to a value like <code>f(3)</code>, you leave out the parentheses and add a space.
# <code>{ x, y ? "foo", z ? "bar", ... }: z + y + x</code> a set pattern, which can also set defaults. ellipse means that the function may receive extra arguments.
So, <code>f(3)</code> in math, is <code>f 3</code> in Nix.
# <code>args@{ x, y, z, ... }: z + y + x + args.a</code> an <code>@</code> pattern which can be used to match extra arguments and store them in the <code>args</code> set.
 
If you want multiple arguments, you can add arguments like this: <code>arg1: arg2: nixExpression</code>, e.g. <code>f x: y: x*y</code>. Applying that function to multiple values is easy: <code>f(3,4)</code> in math, is <code>f 3 4</code> in Nix.
If you apply one argument <code>f 3</code>, a partial function <code>y: 3*y</code>is returned.
 
If the <code>argument</code> is a set like <code>{ hello="world"; a="text"; }</code>, you can pattern-match/destructure it:
 
# <code>{ hello, y ? "foo", z ? "bar", ... }: z + y + hello</code> a set pattern, which can also set defaults. ellipse means that the function may receive extra arguments.
# <code>args@{ hello, y, z, ... }: z + y + hello + args.a</code> an <code>@</code> pattern which can be used to match extra arguments and store them in the <code>args</code> set.


=== Operators ===
=== Operators ===


Lower precedence means a stronger binding; ie. this list is sorted from strongest to weakest binding, and in the case of equal precedence between two operators, the associativity decides the binding.
Lower precedence means a stronger binding; i.e. this list is sorted from strongest to weakest binding, and in the case of equal precedence between two operators, the associativity decides the binding.


{| class="wikitable"
{| class="wikitable"