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:
-
Cons operator (
:)1 : (2 : (3 : [])) -- Equivalent to [1, 2, 3] -
Range notation
[1..10] -- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ['a'..'z'] -- ['a', 'b', 'c', ..., 'z'] -
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:
expressionis the output expressiongeneratorpulls values from a listconditionfilters values (optional)
Examples
-
Basic generator
[x * 2 | x <- [1..5]] -- [2, 4, 6, 8, 10] -
With filtering condition
[x * 2 | x <- [1..10], x `mod` 2 == 0] -- [4, 8, 12, 16, 20] -
Multiple generators (Cartesian product)
[(x, y) | x <- [1, 2], y <- ['a', 'b']] -- [(1,'a'), (1,'b'), (2,'a'), (2,'b')] -
Dependent generators
[(x, y) | x <- [1..3], y <- [x..3]] -- [(1,1), (1,2), (1,3), (2,2), (2,3), (3,3)] -
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
| Lists | Tuples |
|---|---|
| Same type for all elements | Can have different types |
| Variable length | Fixed length |
[Int], [String], etc. | (Int, String), (Bool, Int, Char), etc. |
| Operations like map, filter | Accessed by pattern matching |
Key Points to Remember
- Lists are homogeneous (all elements have the same type)
- Lists can be infinite thanks to lazy evaluation
- List comprehensions provide a powerful, declarative way to create and transform lists
- The cons operator (
:) and empty list ([]) are the fundamental building blocks of lists - Pattern matching on lists typically uses the
(x:xs)pattern