Skip to content
Haskell

List Comprehensions and Laziness

Generate lists with comprehensions and leverage laziness.

By EZ4Code Team
listlazycomprehension

Code

-- List comprehension
squares = [x * x | x <- [1..10]]
evens = [x | x <- [1..100], even x]
pairs = [(x, y) | x <- [1..3], y <- [1..3], x < y]
-- [(1,2),(1,3),(2,3)]

-- Infinite lists (lazy!)
ones = 1 : ones                    -- [1,1,1,...]
nats = [1..]                       -- [1,2,3,...]
fib = 0 : 1 : zipWith (+) fib (tail fib)
-- take 10 fib => [0,1,1,2,3,5,8,13,21,34]

-- take / drop / takeWhile
take 5 [1..]                       -- [1,2,3,4,5]
take 5 (filter even [1..])         -- [2,4,6,8,10]
takeWhile (< 100) (map (*2) [1..]) -- [2,4,...,98]

-- Higher-order
map (*2) [1..5]                    -- [2,4,6,8,10]
filter (>3) [1..5]                 -- [4,5]
foldr (+) 0 [1..100]               -- 5050
zipWith (+) [1,2,3] [10,20,30]     -- [11,22,33]

-- String processing (String = [Char])
wordsLengths = map length . words  -- function composition
wordsLengths "hello world foo"     -- [5,5,3]

Explanation

Haskell is lazy — infinite lists work because values are computed only when needed. [1..] is an infinite list; take n materializes only the first n. Comprehensions are like Python's: generators with filters. foldr processes from the right (good for laziness); foldl from the left. Use Data.List for performance-critical code.

More Haskell Snippets