Nix 101 Course / Section 2: The Nix language
Premium

2.5 Lazy evaluation explained: why 1/0 doesn't crash

Lesson 12 of 68 · 7:42

placeholder thumbnail

Sign in, then buy this course to watch

Free account · no credit card needed

Video chapters

  1. 0:00 Introduction to lazy evaluation
  2. 0:55 Why unused errors don't trigger
  3. 2:30 Using traces to prove laziness
  4. 3:40 Comparing Nix laziness with Python
  5. 5:20 How Nix builds and discards values
  6. 6:50 Why laziness is useful in Nix
Transcript

Introduction to lazy evaluation

0:00 OK, in this video, we're going to talk about lazy evaluation. This is one of the parts of the Nix language that people find typically very strange, especially when you never use functional programming languages. It might sound pretty alien that sometimes code is evaluated in supposedly random order or not at all. And in this video, we're going to demystify that. And you will not only understand how lazy evaluation works, but you will also see why this is actually useful tool in the context of Nix.

0:32 So we have an example here, which should not work if that was ported to Python or other languages. What we do here is we say x equals 1 divided by 0. Of course, that wouldn't work, because that's a division by 0. Same here with that list y, where we add two items that are both divided by 0. So none of this would work.

Why unused errors don't trigger

0:55 Then when we look at the code, it asks if the length of the item y, this list here, is bigger than 1. And if so, then it will print all good. Otherwise, it would print x, which is, of course, another division by 0. So it seems like a little maze to go through where there's more paths that actually trigger an error than not. I have, of course, prepared this already. Let's have a quick look. So here, we wrote down this essential code here. And we can now simply evaluate it, either in the REPL or just with the nix eval command.

The full transcript comes with the lesson.

About this lesson

x = 1 / 0, and evaluation succeeds? Lazy evaluation is the part of the Nix language that feels strangest to newcomers. It also explains 90% of the "wait, why didn't that fail?" moments you will ever have with Nix.

In this video

  • The division by zero puzzle: a snippet that should crash in three places, but prints "all good"
  • Using traces to prove which parts of your code Nix never even looked at
  • Rebuilding the same behavior in Python, so you see laziness in a language you already know
  • A step by step drawing of what Nix builds in memory instead of running your code
  • Why this mechanism lets you import a repository of 100,000 packages in milliseconds

After this lesson

Laziness stops being spooky. You can predict what gets evaluated and when, and that is the skill behind reading any nontrivial Nix code.