2.9 Common idioms: map, filter, foldl' and friends
Lesson 16 of 68 · 11:39
Video chapters
-
0:00 Built-in list functions: filter and map
-
2:40 Using foldl to implement sum
-
5:00 Where to find Nix documentation
-
7:50 Exploring Nixpkgs lib and Noogle
-
10:10 Reading the standard library and avoiding reinvention
Transcript
Built-in list functions: filter and map
0:00 There's so much more Nix code that we haven't seen yet because we have just scratched the surface while learning the syntax and recursion and so on. There's a few other examples I want to show you and then also motivate you where you can find more from the huge Nix packages standard library. Let's have a quick look. For example, the thing is in the REPL, there's things like if you want to filter a list, you could say, okay, let's filter out all the items that will fill some kind of predicate.
0:31 You already know how you would write that recursively yourself, but there's functions for that already. For example, we can say builtins.filter and then we can say filter out all items that are bigger than two or something and then say 100, 2, 20, 30, 10, 1, I don't know, some random values. Now we can see that they filter out the 2 and the 1 and the 0 and we get all these things here.
1:01 So that is already built in. Another interesting function is map, builtins.map. We actually don't have to use the builtins prefix here because that function is being used so often that they're just allowed to use it without. In this case, we can have a mapping of all numbers in the list where we actually take each item one by one and then multiply it with itself, which basically squares it and then get these values out of it.
The full transcript comes with the lesson.
About this lesson
You could write every list operation recursively by hand, but you should not have to. This lesson introduces map, filter and foldl', the everyday idioms of functional programming in Nix, and shows where the huge nixpkgs standard library documents hundreds more.
In this video
builtins.filterandmapin the REPL, plus a first taste of eta reduction- The
sumfunction from the exercise, rewritten in one line withfoldl' - Why Nix has three manuals, and which one to open for what
- noogle.dev, a search engine for Nix functions, with examples and links straight into the nixpkgs source
- The three library files that hold about 80 percent of the functions you will ever need
After this lesson
You stop reinventing the wheel: before writing a helper yourself, you know exactly where to check whether nixpkgs already ships it.
Builds on: Exercise: sum a list with recursion (2.13)
Links: