Nix functions

From wikinotes

Documentation

nix builtin functions https://nixos.org/nix/manual/#ssec-builtins

Lambdas

All functions are lambdas unless they are assigned to a variable.

x:     x       # lambda, with param 'x', that returns 'x'
x: y:  x + y   # lambda, with 2x params
(x: x) "foo"   # invoke lambda, with param "foo"

Functions

my-function = x:     x      # function 'my-function', with param 'x', that returns 'x'
my-function = x: y:  x + y  # function with 2x params
(my-function "foo")         # invoke 'my-function' with param "foo"

Keyword params

my-function { a, b }: c:        # sets within arguments define keyword-arguments
  a + b + c

my-function {a="A"; b="B"} "C"  # invocation using set-param requires a set
"ABC"

Default param values

my-function { a ? "A", b ? "B" }  # '?' assigns a default param
  a + b

my-fn {a="A"}
"AB"

Optional keyword params with '@attrs'

fn = attrs@{ a, b, ...}: a + b + attrs.c   # attrs variables are accessed from their namespace

fn { a="A" b="B" c="C" }                   # invocation for 'attrs@' requires set
"ABC"

Calling Functions

fn "arg1" "arg2"   # call 'fn' with arguments
fn {}              # call 'fn' with empty hash as argument (if it expects a hash)

foo = readFile (fn);  # functions between brackets are evaluated first

currying

Nix technically only ever accepts a single function at a time.
But variables are accessible in nested functions.
Multiple params are just stacked functions that each require a different param.

greet = name: age: "hello ${name}, age ${age}"
greet { name = "alex", age = 30 }
#> helllo alex, age 30

map/filter

map

map (x: "foo" + x) [ "bar" "bla" "abc" ]
# [ "foobar" "foobla" "fooabc" ]

filter

vars = [ cat hat tab bat fab ]
builtins.filter (x: builtins.isList(builtins.match ".*at$" x)) var
# [ cat hat bat ]

Assert

assert foo  # asserts foo has val

Datatype Specific

Be sure to also see nix datatypes for datatype specific functions.