Kitaab

Nix the Language

nix

published 2019-09-21 14:02

updated 2023-06-06 21:43

Trying to understand the Nix Language

Nix is a functional source grabber and builder. It's not really a package manager, only incidentally so. (Nixpkgs notwithstanding?)

nix repl is your friend!

AttrSets

The building block datastructure in Nix. Basically just a DictionarySet

{
    <attributes> = ...;
}

Functions

Nix functions work kinda like Haskell, but no types
> double = x: x*2
> double 2
> 4

Since nix is fucking Haskell, arguments get passed through currying

> add = x: y: x + y
> add 2 3
> 5

It's good practice to pass arguments as AttrSets You can also pass default arguments But functions take exactly what they define. Nothing more, nothing less.

> add = {x, y ? 2}: x+y
> add {x = 2;}
> 4
> add {x=2; y=3}
> 5

If you want other thigs you can do it this way

> add = s@{x, y, ...}: x + y + s.z
> add {x=2;y=2;z=1;a=1;}
> 5

Builtins

Nix comes with a lot of builtin functions, but doesn't want to pollute scope. So most the functions are scoped under `builtins.` 
https://nixos.org/manual/nix/stable/#ssec-builtins

Derivations

One of the functions that Nix includes in all scopes is the `derivation` function
It takes a few arguments, does some Nix magic, and produces a `Derivation`. Kinda like a .o file in C or the .class file in Java. It's not quite a real package yet. Nix still needs to build it

builder
name
output

Nixpkgs

nix-store

Building process

/tmp
$PATH, $HOME
outs

Flakes

NixOS

Modules

Backlinks