TExcelTAD
Home › Haskell › Haskell Lists & Ranges

Haskell Lists & Ranges

The list is Haskell's workhorse data structure. A list holds any number of values of the same type, written in square brackets: [3, 1, 4] has type [Int] (or more generally Num a => [a]), and ["a", "b"] has type [String].

haskell · try it yourself
main :: IO ()
main = do
  let primes = [2, 3, 5, 7, 11]
      words' = ["sun", "moon", "star"]
      empty = [] :: [Int]
  print primes
  print words'
  print (length primes, length empty)
  print (null empty, null primes)
[2,3,5,7,11]
["sun","moon","star"]
(5,0)
(True,False)

Building lists: : and ++

Under the hood a list is either empty ([]) or an element put in front of another list with the cons operator :. The bracket syntax is just shorthand: [1, 2, 3] means 1 : 2 : 3 : [].

haskell · try it yourself
main :: IO ()
main = do
  let rest = [2, 3]
  print (1 : rest)                -- add to the front: cheap
  print (1 : 2 : 3 : [])
  print (rest ++ [4, 5])          -- concatenate: walks the left list
  print ('H' : "askell")          -- strings are lists of Char
  print (concat [[1], [2, 3], []])
[1,2,3]
[1,2,3]
[2,3,4,5]
"Haskell"
[1,2,3]

Note: Haskell lists are singly linked lists, not arrays. Adding to the front with : is instant; xs ++ ys has to copy all of xs; and xs !! n (indexing) walks n steps. For fast indexing use Data.Array, Data.Vector (a package) or Data.Map.

Taking lists apart

haskell · try it yourself
main :: IO ()
main = do
  let xs = [10, 20, 30, 40, 50]
  print (head xs, last xs)
  print (tail xs)
  print (init xs)
  print (xs !! 2)               -- index from 0
  print (take 2 xs, drop 2 xs)
  print (splitAt 3 xs)
  print (reverse xs)
  print (elem 30 xs, 99 `elem` xs)
(10,50)
[20,30,40,50]
[10,20,30,40]
30
([10,20],[30,40,50])
([10,20,30],[40,50])
[50,40,30,20,10]
(True,False)

head, tail, last, init and !! crash on lists that are too short (head [] is a runtime error). GHC 9.12 even warns about head and tail for that reason. Later lessons show the safer alternatives: pattern matching and functions that return Maybe.

Useful list functions

Function Example Result
sum, product product [1, 2, 3, 4] 24
maximum, minimum maximum [3, 9, 2] 9
zip zip [1, 2] "ab" [(1,'a'),(2,'b')]
replicate replicate 3 'x' "xxx"
map map (* 2) [1, 2, 3] [2,4,6]
filter filter even [1 .. 6] [2,4,6]
and, or and [True, False] False
concat concat ["ab", "cd"] "abcd"
haskell · try it yourself
main :: IO ()
main = do
  let scores = [72, 95, 88, 61, 79]
  print (sum scores, maximum scores, minimum scores)
  print (map (+ 5) scores)
  print (filter (>= 80) scores)
  print (zip ["Ann", "Bob", "Cat"] scores)
  print (replicate 4 '*')
(395,95,61)
[77,100,93,66,84]
[95,88]
[("Ann",72),("Bob",95),("Cat",88)]
"****"

Notice that zip stops at the shorter list: the extra scores are dropped.

Ranges

A range generates an arithmetic sequence. Give the first element and the last, and optionally the second element to set the step:

haskell · try it yourself
main :: IO ()
main = do
  print [1 .. 10]
  print [2, 4 .. 20]         -- step of 2
  print [10, 8 .. 1]         -- counting down needs an explicit step
  print ['a' .. 'f']         -- works for any enumerable type
  print [5 .. 1]             -- empty: no implicit counting down
  print (take 5 [100 ..])    -- an infinite range
[1,2,3,4,5,6,7,8,9,10]
[2,4,6,8,10,12,14,16,18,20]
[10,8,6,4,2]
"abcdef"
[]
[100,101,102,103,104]

Tip: Avoid floating-point ranges such as [0.1, 0.2 .. 1.0]. Rounding errors make the last element surprising (the range may go slightly past 1.0). Generate integers and divide instead: map (/ 10) [1 .. 10].

Lists are immutable

None of these functions change a list; they return a new one. The original is still there, unchanged, which is why it is safe to share lists between functions:

haskell · try it yourself
main :: IO ()
main = do
  let original = [3, 1, 2]
      longer = 0 : original
      sortedish = reverse original
  print original
  print longer
  print sortedish
[3,1,2]
[0,3,1,2]
[2,1,3]

longer doesn't copy original: it is a new cell pointing at the existing list. Immutability makes that sharing safe and cheap.

Test yourself

What is [1, 2, 3] shorthand for?

  1. 1 ++ 2 ++ 3
  2. 1 : 2 : 3 : []
  3. (1, 2, 3)
  4. [1] : [2] : [3]

What is [10, 7 .. 0]?

  1. [10,7,4,1]
  2. [10,7,4,1,0]
  3. []
  4. [10,9,8,7]

Which operation is cheap (constant time) on a Haskell list?

  1. xs !! 1000
  2. xs ++ [x]
  3. x : xs
  4. last xs