-
Notifications
You must be signed in to change notification settings - Fork 0
Nix Language Reference
Marcus Whybrow edited this page Aug 24, 2024
·
1 revision
{}
👆 That's the simplest bit of nix! Nix is really simple.
# example.nix
{
whatCanNixDo = "It can store data";
whatAreTheCurlyBrackets = "They define a set of key value pairs known as attributes";
amIAnAttribute = "Yes, you are the third attribute in this attribute set";
whichAttributeAmI = 4;
soYouCanStoreNumbersAlso = true;
andBooleanValuesToo = {
yes = "You can store boolean values";
andAlso = "You can store atrribute sets within attribute sets!";
};
"can key names have spaces" = "Sure";
whatAboutLists = [
"lists can contain anything separated by a space, such as:"
20 21 22
false
];
}
The nix
command can pull from this data:
nix eval --file example.nix whatCanNixDo # "It can store data"
nix eval --file example.nix whichAttributeAmI # 4
nix eval --file example.nix andbooleanValuesToo.yes # "You can store boolean values"
nix eval --file example.nix "can key names have spaces" # Sure
nix eval --file example.nix whatAboutLists.2 # 20
You can use the attributes of a set as variables for use within that set, by using the rec
keyword:
rec {
ten = 10;
nine = ten - 1;
five = nine - 4;
zero = ten - 10;
}
When you want to resuse data that you don't want to expose as an attribute, you can "let" a variable exist "in" the scope of a particular attribute set during the evaluation which won't itself become an attribute of the set.
let
activity = "writing Nix!";
in {
onMonday = "On Monday I shall be " + activity;
onTuesday = "And On Tuesday I'll likely try " + activity;
onWednesday = "Ooo I don't know, maybe more " + activity;
}
Nix comes with many builtin functions.
rec {
twentyThreePointThreeFour = 23.34;
twentyThree = builtins.ceil twentyThreePointThreeFour;
twentyFour = builtins.floor twentyThreePointThreeFour;
}
And you can declare your own functions too.
let
subtractOne = number: number - 1;
multiplyThenSubtractOne = firstNumber: secondNumber: firstNumber * secondNumber - 1;
in {
ninetyNine = subtractOne 100;
five = subtractOne 6;
eleven = multiplyThenSubtractOne 2 6;
}