Haskell Infinite Lists
An infinite list is a list with no end that Haskell builds one element at a time. It is safe to use when a program takes only a finite part of it.
Take gives a finite start
The range [1..] has no end. Taking three elements gives a short finished list.
main :: IO ()
main = print (take 3 [1..])A step range can be taken too
The range [10,20..] steps by ten. Taking five elements gives five stepped numbers.
main :: IO ()
main = print (take 5 [10,20..])Iterate builds a doubling list
Iterate starts at 1 and doubles each time. Taking five elements gives the first five doublings.
main :: IO ()
main = print (take 5 (iterate (* 2) 1))Example
main :: IO ()
main = do
print (take 5 (map (* 3) [1..]))
print (take 4 (cycle [7, 8]))Key points
- Range: [1..] counts upward without end.
- Take: take n keeps only the first n elements of a list.
- Repeat: repeat x makes a list that holds x forever.
- Cycle: cycle xs repeats a short list forever.
- Iterate: iterate f x applies f again and again from x.
In this example, the first print maps multiplication by 3 over the counting list and takes five results. The second print cycles the short list 7 and 8 and takes four results.
Note
printing a whole infinite list never finishes, so always take a finite part first.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does take 3 [1..] give?