...

/

Introduction to Lists

Introduction to Lists

Get introduced to the list datatype.

In the next lessons, we will study the list datatype, the essential datatype of Haskell and functional programming in general. As lists are defined recursively themselves, they fit well to a language that uses recursion as its primary problem solving technique.

The list datatype

A list is a linear data structure for a collection of elements. Each element points to the next element, except the last element, which points to a special nil value (the empty list). Here is a visualization of a list containing the three numbers 1, 2, 3.

%0 node_1 1 node_2 2 node_1->node_2 node_3 3 node_2->node_3 node_1600679769445 node_3->node_1600679769445
A list of three numbers.

Just like tuples, we can make lists from any Haskell data type. List types are denoted using square brackets. A list of integers has the type [Int], a list of doubles the type [Double], and so on. To make list literals, we can simply enumerate values in square brackets. Here are some examples of lists:

ints :: [Int]
ints = [1, 2, 3]

empty :: [Int]
empty = []

functions :: [Int -> Int]
functions = [(+1), (*2)]

nested :: [[String]]
nested = [["hi"], ["how", "are", "you"], ["i'm", "fine"]]

As the examples show, we can make lists ...