🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Lists

A list is an ordered collection of values of the same type, written inside square brackets. Lists are how a Haskell program holds a group of numbers, pieces of text, or other values.

A list keeps values in order

This list literal holds three numbers. The printed form keeps that order and uses no spaces after commas.

main :: IO ()
main = print [3, 1, 4]

Cons adds a value to the front

The : operator places 0 before the values already in the list.

main :: IO ()
main = print (0 : [1, 2, 3])

Joining puts two lists together

The ++ operator puts the second list after the first list.

main :: IO ()
main = print ([1, 2] ++ [3, 4])

Head gives the first value

The head of this list is its first number.

main :: IO ()
main = print (head [8, 6, 4])

Example

scores = [40, 50, 60]

main :: IO ()
main = print (tail (10 : scores))

Key points

  • List literal: values sit inside square brackets, separated by commas.
  • Same type: every value in a list shares one type.
  • Cons operator: the : operator adds one value to the front of a list.
  • Join operator: the ++ operator joins two lists into one list.
  • Head function: head gives the first value in a list.
  • Tail function: tail gives a list with the first value removed.

In this example, scores is the list [40, 50, 60]. The : operator adds 10 to the front, and tail then removes that first value, so print shows the original three scores.

Note

a string is a list of characters, so list ideas also apply to text.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What is the value of 2 : [3, 4]?