Haskell Ranges
A range is a shorthand for a list of values that follow a pattern. Ranges can count by one, step by a fixed amount, run downward, or run through characters.
A basic range counts by one
The two dots give every whole number from 1 up to 5.
main :: IO ()
main = print [1..5]A second value sets the step
The values 1 and 3 set a step of two, up to 9.
main :: IO ()
main = print [1,3..9]A character range builds text
The letters from a to e form one text value, and print shows it with double quotes.
main :: IO ()
main = print ['a'..'e']A range can count down
The values 10 and 9 set a downward step of one, down to 1.
main :: IO ()
main = print [10,9..1]Example
main :: IO ()
main = print (take 4 [100..])Key points
- Basic range: [1..5] builds the list of whole numbers from 1 to 5.
- Step range: writing a second value, as in [1,3..9], sets the size of each step.
- Character range: ['a'..'e'] builds the text made of the letters from a to e.
- Downward range: [10,9..1] counts down because its first step goes downward.
- Endless range: [1..] has no final value and never ends on its own.
- Take with a range: take keeps only the requested first values, so an endless range stays safe under take.
In this example, the endless range starts at 100 and counts up by one. take 4 keeps only the first four values, so print shows those four and the program ends.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What is the value of [2,4..10]?