Lists and String Sequences
Introduction: Grouping Data in Haskell
Welcome to Unit 2! In our first unit, we focused on pattern matching and working with single, isolated values such as individual numbers and characters. However, when writing real-world programs, we rarely deal with just one of something. We have lists of user IDs, lines of text, and groups of settings.
In Haskell, the primary way to group items together is by using a sequence called a list. A list allows us to store multiple pieces of data in a specific order, provided that all items share the same type. In this lesson, we will learn how to create lists, add new elements to them, combine them, and display them on the screen.
Building and Growing Lists of Numbers
Let's start by creating a simple list of whole numbers. In Haskell, we write a list by placing our items inside square brackets, separated by commas.
Here, we define a variable named numbers. The type signature [Int] tells Haskell that this is a list containing integers.
We often need to add new data to an existing list. We can add a single item to the very front of a list using the cons operator, which is written as a single colon (:).
In this code, 0 : numbers takes the number 0 and attaches it to the front of the numbers list.
Sometimes, we want to combine two complete lists rather than just adding a single item. We can join two lists together using the concatenation operator, which is written as two plus signs (++).
Here, numbers ++ [4, 5] takes our original list and attaches [4, 5] to the end of it.
There is a very important rule to remember regarding how Haskell handles data: lists are permanent, or immutable. When we use : or ++, we are not changing the original numbers list. Instead, Haskell creates brand-new lists for withZero and moreNumbers. The original numbers list remains exactly [1, 2, 3].
The Secret Identity of Strings
Now that we know how lists work, we can uncover a fundamental rule in Haskell: a standard text String is simply a list of characters behind the scenes.
Let's prove this by starting with a list of individual characters, which has the type [Char]. Notice that single characters use single quotes.
Because a String is identical to a [Char] list, we can use our list operators on text. Let's use the concatenation operator (++) to join our character list with a standard string literal.
In this code, "!" is a String, which means it is treated as ['!']. Because letters is also a list of characters, ++ works perfectly to join them into a new String called greeting.
