Lists are one of the most fundamental data structures in Haskell. They store sequences of elements of the same type.

See also: Pattern Matching and Recursion, Algebraic Data Types, Polymorphism, Higher-Order Functions

List Basics

Syntax

Lists in Haskell are written with square brackets and commas:

[1, 2, 3, 4, 5] :: [Int]
["Hello", "FP", "Students"] :: [String]

List Construction

Lists can be constructed in several ways:

  1. Cons operator (:)

    1 : (2 : (3 : []))  -- Equivalent to [1, 2, 3]
  2. Range notation

    [1..10]  -- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    ['a'..'z']  -- ['a', 'b', 'c', ..., 'z']
  3. Infinite lists

    [1..]  -- [1, 2, 3, 4, ...] (thanks to lazy evaluation)

List Manipulation

Basic operations for accessing lists:

head [1, 2, 3]  -- 1
tail [1, 2, 3]  -- [2, 3]
[1, 2, 3] !! 1  -- 2 (0-indexed)

Warning: These functions are partial (can fail with an error on empty lists).

List Comprehensions

List comprehensions provide a concise syntax for creating lists based on existing lists.

See: Pattern Matching and Recursion, Property-Based Testing

Basic Syntax

[expression | generator, condition]

Where:

  • expression is the output expression
  • generator pulls values from a list
  • condition filters values (optional)

Examples

  1. Basic generator

    [x * 2 | x <- [1..5]]  -- [2, 4, 6, 8, 10]
  2. With filtering condition

    [x * 2 | x <- [1..10], x `mod` 2 == 0]  -- [4, 8, 12, 16, 20]
  3. Multiple generators (Cartesian product)

    [(x, y) | x <- [1, 2], y <- ['a', 'b']]  -- [(1,'a'), (1,'b'), (2,'a'), (2,'b')]
  4. Dependent generators

    [(x, y) | x <- [1..3], y <- [x..3]]  -- [(1,1), (1,2), (1,3), (2,2), (2,3), (3,3)]
  5. Pythagorean triples

    [(x, y, z) | x <- [1..10], y <- [x..10], z <- [y..10], x^2 + y^2 == z^2]

List Operations

See: Higher-Order Functions, Functors and Applicatives

List Concatenation

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

List Zipping

zip [1, 2, 3] ["one", "two", "three"]  -- [(1,"one"), (2,"two"), (3,"three")]
zipWith (+) [1, 2, 3] [4, 5, 6]  -- [5, 7, 9]

Lists vs. Tuples

See: Algebraic Data Types

ListsTuples
Same type for all elementsCan have different types
Variable lengthFixed length
[Int], [String], etc.(Int, String), (Bool, Int, Char), etc.
Operations like map, filterAccessed by pattern matching

Key Points to Remember

  1. Lists are homogeneous (all elements have the same type)
  2. Lists can be infinite thanks to lazy evaluation
  3. List comprehensions provide a powerful, declarative way to create and transform lists
  4. The cons operator (:) and empty list ([]) are the fundamental building blocks of lists
  5. Pattern matching on lists typically uses the (x:xs) pattern

See: Pattern Matching and Recursion