Nix 101 Course / Section 2: The Nix language
Premium

2.6 Lists and recursion in Nix

Lesson 13 of 68 · 13:22

placeholder thumbnail

Sign in, then buy this course to watch

Free account · no credit card needed

Video chapters

  1. 0:00 Intro to the exercises
  2. 0:52 Working with lists in Nix
  3. 3:34 List concatenation and precedence
  4. 5:57 Recursion with Fibonacci
  5. 9:23 Combining recursion with lists
Transcript

Intro to the exercises

0:00 This video is a preparation for the upcoming exercises. We have two quick exercises. So if you already are fed up with learning the language and the syntax and finally want to build some packages, this will be quick anyway. Or if you actually needed that additional practice, then we'll take some more time. However, after this section and after the exercises, we'll be prepared to write actual real-life Nix code. And never be confused by the syntax again.

0:32 So let's start. What's still needed is we need to know how to handle lists. We'll play around with this in the REPL. What's just here to know is that, like in other languages, you use angle brackets to define a list. But there's no comma between the items. And then there's the functions built in length, head, and tail.

Working with lists in Nix

0:53 Length, of course, gives us the length number of the list. And head and tail are interesting, because head gives us the first item. And the tail gives us all items after the first. You could imagine this like a snake, right? From the snake, if you remove the head and just take that, that's the head. And the tail of a snake is basically everything without the head. Let's play around with this quickly. So we can just launch a REPL and say list equals 1, 2, 3.

The full transcript comes with the lesson.

About this lesson

Nix has no for loops, so lists and recursion do the work that loops do elsewhere. This lesson shows how to take lists apart with head and tail, glue them back together with ++, and set up a recursive function in a language where every file is one single expression.

In this video

  • builtins.length, head and tail, and the exception waiting for you on the empty list
  • Two syntax pitfalls: operator precedence around ++, and why x-1 is a variable name, not a subtraction
  • A Fibonacci function, and the let in trick that lets a function call itself by name
  • Walking a list recursively with trace output, and the lazy evaluation detail that keeps it from crashing

After this lesson

You can decompose, rebuild and recurse over lists, which is exactly what the next two exercises assume you can do.