functions.md

Functions

Before this, you'll want

  1. Sets and decisions
The Nix language11 min

A function is a little machine. Give it a value, and it gives you a new value.

In Nix, a colon : separates the parameter, the local name that receives the input, from what comes back:

nix replevaluated as you typeNixA plain Nix expression. Nothing from nixpkgs or a module system is supplied.

Right now the result says «lambda». The machine exists, but we haven’t put anything into it yet.

Calling a function

Put an argument after the function. That is the value fed into its parameter. No commas, and no brackets needed.

Try it

Replace 5 with 7, so the function adds it to 10.

nix replevaluated as you typeNixA plain Nix expression. Nothing from nixpkgs or a module system is supplied.

The value gets transformed and the whole expression turns into our result!

mynumber is a custom parameter name. It only exists inside the function.

Usually you name a function with let, so you can call it more than once.

nix replevaluated as you typeNixA plain Nix expression. Nothing from nixpkgs or a module system is supplied.

double stays a simple multiplication function. The set can reuse it for both money and joy.

Functions are also easy to chain. Use each one to transform the last value, then add a few more and see where it ends up.

nix replevaluated as you typeNixA plain Nix expression. Nothing from nixpkgs or a module system is supplied.

Dropping values into strings

Now for the piece of syntax you are going to type more often than any other.

${...} is interpolation. It evaluates whatever is inside and places the result into a string or an attribute name.

nix replevaluated as you typeNixA plain Nix expression. Nothing from nixpkgs or a module system is supplied.

Interpolation becomes especially handy inside functions:

Try it

Make the greeter say "hello, world!".

nix replevaluated as you typeNixA plain Nix expression. Nothing from nixpkgs or a module system is supplied.

Two inputs

One input runs out of usefulness quickly. Write two parameter names to feed a function two values:

nix replevaluated as you typeNixA plain Nix expression. Nothing from nixpkgs or a module system is supplied.

Read add 20 22 from left to right: give it 20, then 22. Underneath, Nix does this one input at a time. The nice part is that calls stay pleasantly short.

Try it

Change the second argument to 3 to shout the battle cry three times.

nix replevaluated as you typeNixA plain Nix expression. Nothing from nixpkgs or a module system is supplied.

What to keep

  • input: result creates a function.
  • function value calls one.
  • first: second: result handles inputs one at a time.
  • ${...} drops a calculated value into a string.
  • Use a let binding to make a function reusable.

Useful links

NORMALCOURSE IN BETA