Nix datatypes

From wikinotes

Documentation

builtins src
strings src https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix
lists src https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix
attrsets src https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix

Null

null

Boolean

true
false

Strings

See https://github.com/NixOS/nixpkgs/blob/master/lib/strings.nix

"hello"             # a string
"hello" + " world"  # concatenate string

# multiline string
'' 
line A
line B
line C 
''

# interpolated strings
"${name}-${version}"
# functions
pkgs = import <nixpkgs> {}
pkgs.lib.strings.splitString "\n" "a\nb\nc"                   # ["a" "b" "c"]
pkgs.lib.strings.concatStrings ["ab" "cd" "ef"]               # "abcdef"
pkgs.lib.strings.concatMapStrings (x: x + ",") ["a" "b" "c"]  # "a,b,c,"

# building software
makePackagePath = pkgs.stdenv.lib.makeSearchPathOutput "" "";
makeIncludePath = pkgs.stdenv.lib.makeSearchPathOutput "include" "include";
makePackagePath [ pkgs.zlib pkgs.libxml2 ]                 # /nix/store/..-zlib-1.2.11/:/nix/store/..-libxml2-2.9.10/
makeIncludePath [ pkgs.zlib pkgs.libxml2 ]                 # /nix/store/..-zlib-1.2.11/include:/nix/store/..-libxml2-2.9.10/include

pkgs.stdenv.lib.makeLibraryPath [ pkgs.zlib pkgs.libxml2 ] # /nix/store/zlib-1.2.11/lib:/nix/store/libxml2-2.9.10/lib
pkgs.stdenv.lib.makeBinPath [ pkgs.zlib pkgs.libxml2 ]     # /nix/store/zlib-1.2.11/bin:/nix/store/libxml2-2.9.10/bin

Numbers

123  # integer
# NOTE no floating-point numbers

Paths

All paths are translated to absolute paths.

./file.txt        # relative path (note no quotes)
/a/b/c/file.txt   # absolute paths

Collections

Lists

See Examples of common list operations https://github.com/NixOS/nixpkgs/blob/master/lib/lists.nix

[ 1 "two" 3 ]       # list (0-indexed)
[ 1 2 ] ++ [ 3 4 ]  # extend list

builtins.elemAt [ 1 2 3] 1  # retrieve item at index-1

pkgs.lib.lists.subtractLists [ 1 2 ] [ 1 2 3 4 ]  #== [ 3 4 ]

AttrSets

In nix, sets are mappings. https://github.com/NixOS/nixpkgs/blob/master/lib/attrsets.nix

{ a = 0; b = "foo"; }    # map
{ a = 0; b = "foo"; }.b  # retrieve value for key 'b'

Recursive Sets

recursive sets allow attributes to refer to other attributes within the same set.

rec {     # rec keyword defines set as recursive
  a="A";
  b=a;    # <--
};