2.7 Exercise: sum a list with recursion
Lesson 14 of 68 · 5:42
Video chapters
-
0:00 Introduction to the Nix recursion exercises
-
0:47 Designing the sum function and base case
-
2:06 Recursive implementation with head and tail
-
3:51 Testing the function in the Nix REPL
Transcript
Introduction to the Nix recursion exercises
0:00 Okay, it's exercise time now. Let's try how good we are with Nix syntax and recursion now in two short exercises. Of course, they will be short if it's easy, and if it turns out not to be that easy, then it's good to bite through it, because this way we will be well prepared to actually do write real life Nix code. First exercise that will be, we write a function that sums up a list. So it accepts a list of numbers, like one list, that would be one parameters, and returns us the sum.
0:38 We'll put the implementation to a file and then try it out in the REPL. We'll have a quick example for that how this will look like before we go.
Designing the sum function and base case
0:47 And the test cases, for example, would be like this or like an example how this function will look like when it's implemented. We will say sum and then give it a list, right? In this example, it contains numbers one, two, three. Of course, the sum of numbers one, two, three would be six. And the sum of an empty list, we would just define it to be zero. Otherwise, where do we stop the recursion? Useful functions that we will need are the built-in functions, head and tail at least.
The full transcript comes with the lesson.
About this lesson
Time to write your first recursive Nix function yourself. The task: a sum function that takes a list of numbers and returns their total. No loops, no mutation, just recursion. It sounds small, and that is the point: this is the pattern behind real Nix code everywhere.
In this video
- The exact task and test cases, including what
sumof an empty list should return - The only hints you need:
head,tail, and checking for the empty list first - A pause point to solve it on your own before the walkthrough begins
- A trace added to the finished function so you can watch the numbers add up, call by call
After this lesson
Once you have written this function with your own hands, the recursion pattern stops being theory and becomes something your fingers know.
Links: