Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 57 ยท Types and values

Tuples and Lists

Learn Haskell tuples and lists: fixed-size tuples with fst and snd, list literals, the cons operator, ranges, and head, tail, take and drop.

Almost every Haskell program passes around small bundles of values and sequences of values. For the first you use tuples, for the second lists. They look similar on the page, with brackets and commas, but they behave very differently, and the type checker cares about the difference.

In this lesson you will build both, learn the handful of list functions you will use every day, and see how ranges and the cons operator : work. If the type notation below looks unfamiliar, read Basic Types and Type Signatures first.

Haskell is not installed on this site, so the Haskell snippets are read-only. The runnable editors use JavaScript stand-ins: arrays play the role of lists and tuples. Each one says what is real Haskell and what is imitation.

Tuples: a fixed number of values

A tuple groups a fixed number of values, and each position can have a different type.

HASKELL
point :: (Double, Double)
point = (3.0, 4.5)

person :: (String, Int, Bool)
person = ("Ada", 36, True)

The type of a tuple lists the type of every position. (Double, Double) is a different type from (Double, Double, Double), and (Int, String) is different from (String, Int). The number and order of components are part of the type.

For pairs (two-element tuples) the Prelude gives you two accessors:

HASKELL
fst ("x", 10)   -- "x"
snd ("x", 10)   -- 10

fst and snd work only on pairs. For bigger tuples you use pattern matching, which you will meet soon:

HASKELL
let (name, age, _) = ("Ada", 36, True)

Tuples are handy for returning more than one result from a function, or for temporary pairs such as (key, value). When a bundle gets more than three or so components, or when the meaning of each position is not obvious, define a record instead.

The empty tuple () is called unit. It has exactly one value, also written (), and it is used where you must return "nothing interesting", most often in IO ().

Lists: any number of values of one type

A list holds zero or more values, all of the same type. The type [Int] means "list of Int". Write a list with square brackets:

HASKELL
primes :: [Int]
primes = [2, 3, 5, 7, 11]

empty :: [String]
empty = []

-- Not allowed: mixed types
-- bad = [1, "two", True]

The type is the key difference. A tuple has a fixed size and mixed types. A list has any size and one type. If you need both a name and an age for ten people, that is a list of tuples: [(String, Int)].

HASKELL
team :: [(String, Int)]
team = [("Ada", 36), ("Linus", 55), ("Grace", 85)]

Strings are lists

String is just a type synonym for [Char], so every list function also works on text. "hello" is the same list as ['h','e','l','l','o']. The Strings, Chars and Text lesson goes deeper.

Building lists with cons

A Haskell list is a singly linked list. It is either empty ([]) or a head element attached to another list. The operator that attaches an element to the front is :, pronounced "cons".

HASKELL
0 : [1, 2, 3]        -- [0,1,2,3]
1 : 2 : 3 : []       -- [1,2,3]

The second line shows what [1, 2, 3] really is: shorthand for 1 : (2 : (3 : [])). The operator : is right associative, so no parentheses are needed.

Because adding to the front only creates one new link, x : xs is fast, constant time. Joining two lists with ++ has to copy the first list, so its cost grows with the length of the left side.

HASKELL
[1, 2] ++ [3, 4]     -- [1,2,3,4]

Prefer : when you can, and keep the long list on the right of ++.

Ranges

You rarely type long lists by hand. Ranges build them for you:

HASKELL
[1 .. 5]        -- [1,2,3,4,5]
[2, 4 .. 10]    -- [2,4,6,8,10]
[10, 8 .. 1]    -- [10,8,6,4,2]
['a' .. 'e']    -- "abcde"

The second form gives the first two values, and Haskell works out the step. A descending range needs the step to be written out: [10 .. 1] is empty, because the default step is +1.

Ranges also work without an upper bound: [1 ..] is the infinite list of all positive integers. That is safe because Haskell is lazy and only computes what you use. Lazy Evaluation explains how.

Be careful with ranges of Double. [0.1, 0.2 .. 0.5] can include surprising values at the end because of floating-point rounding. Prefer ranges over Int or Integer and convert afterwards.

Tuple or list?

Tuple Fixed size, mixed types.
List Any length, one type.

The size of a tuple is part of its type. A list's length is not.

1 / 2

The everyday list functions

The Prelude includes dozens of list functions. These are the first ones to learn.

HASKELL
head [10, 20, 30]      -- 10
tail [10, 20, 30]      -- [20,30]
take 2 [10, 20, 30]    -- [10,20]
drop 2 [10, 20, 30]    -- [30]
length [10, 20, 30]    -- 3
null []                -- True
reverse [1, 2, 3]      -- [3,2,1]
sum [1, 2, 3]          -- 6
elem 20 [10, 20, 30]   -- True
[10, 20, 30] !! 1      -- 20  (zero-based index)

A few things to know:

  • head and tail crash on the empty list. head [] throws an exception at run time. They are partial functions: they are not defined for every input. Production code usually matches on the list with pattern matching instead, or uses safe alternatives such as Data.List.uncons or take 1.
  • take and drop are forgiving. take 10 [1, 2, 3] is [1,2,3] and drop 10 [1, 2, 3] is []. They never fail.
  • !! is zero-based and also partial: an index out of range throws. Needing it often is a hint that a different structure, such as Data.Map or an array, would suit you better. See Essential Libraries.
  • length, sum and friends must walk the whole list. That is fine for small lists, but remember a list is a linked chain, not an array.

A stand-in you can run

The editor below imitates these functions on JavaScript arrays. The functions are written by hand, curried like their Haskell cousins would be, and show prints values in Haskell's style. This is a stand-in: real Haskell lists are lazy linked lists, and the real functions live in the Prelude.

JS Tuples and lists with JavaScript arrays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Change team or the range bounds and rerun. Notice that take and drop never complain about going past the end, just like the real ones.

Zipping lists into a list of pairs is a common use of tuples. Real Haskell spells it zip [1,2,3] "abc", giving [(1,'a'),(2,'b'),(3,'c')]. The stand-in below does the same and also splits a list of pairs back with unzip.

JS zip, unzip and lookup

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The real lookup returns Maybe b: Just "b" or Nothing. You will model that properly in Maybe and Either.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of the value (1, "one", True)?

    A tuple may mix types, and its type lists each component in order. A list would require all elements to share one type.
  2. 2. What does [1, 2, 3] stand for when written with the cons operator?

    List literal syntax is shorthand for repeated cons ending in the empty list. The elements keep their order.
  3. 3. What does take 10 [1, 2, 3] return?

    take returns at most n elements and does not fail when the list is shorter. head and tail are the ones that crash on an empty list.
  4. 4. Which list function is a partial function that crashes on []?

    head has no sensible answer for an empty list, so it throws an error. length, drop and reverse are defined for every list.
  5. 5. What is [10 .. 1]?

    A range counts upward by default. To count down, give the step explicitly: [10, 9 .. 1].

Summary

  • A tuple has a fixed size and may mix types; its size and component types are part of its type. fst and snd work only on pairs.
  • A list has any length and a single element type; String is [Char].
  • x : xs adds to the front in constant time; xs ++ ys copies the left list.
  • Ranges such as [1 .. 5], [2, 4 .. 10] and [1 ..] create lists, and the infinite form is safe because of laziness.
  • head, tail and !! are partial; take and drop are always safe.

Next, learn a compact way to build lists from other lists: List Comprehensions.