Safe List Operations
Introduction: Working Safely With Lists
Welcome to Unit 3! In our previous lesson, we learned how to group data together using lists. Now that you know how to build a list, the natural next step is learning how to work with it. How do we find out its size, take a slice of its items, or read specific values?
When writing code, especially as a beginner, it is very common to run into errors that cause a program to crash. For example, asking a computer for the first item of an empty list is a classic way to crash an application.
In this lesson, we are going to focus on performing list operations safely. We will use what are called "total functions" — which simply means these functions are safe to use because they know exactly how to handle every possible input, including empty lists. By the end of this lesson, you will know how to query lists safely and write your own custom function to read from a list without ever risking a crash.
Handy Built-In List Functions
Haskell comes with several built-in tools that are totally safe to use on any list. Let's look at five common ones: length, null, take, drop, and reverse.
First, let's define a simple list of integers that we will use for our examples.
Now, let's start building our main program step-by-step. We will begin by checking the list's size and seeing if it is empty.
Output:
lengthcounts how many items are in the list. Our list has four numbers, so it prints4.nullchecks if the list is completely empty. Since our list has items in it, it printsFalse.
Next, let's look at how we can slice our list. We can grab a few items from the start, or skip a few items to keep the rest.
Output:
take 2safely grabs the first two items, giving us[10, 20].drop 2safely skips the first two items and keeps the rest, giving us[30, 40].
Even if you asked to take 100 from this short list, the program will not crash. It will just safely give you the four items it has.
Finally, we can easily flip the list around using reverse.
Output:
The reverse function flips the order of our list backwards. Like the others, it handles empty lists perfectly well (reversing an empty list simply gives you an empty list back).
