List Comprehensions aren't mentioned on the AQA syllabus, but they're too powerful a feature not to take a look at. It's worth understanding how they work: similar functionality has been introduced into languages such as Java. Let's start with some ranges
```haskell
Prelude> [1..5]
[1,2,3,4,5]
Prelude> [1,3..10]
[1,3,5,7,9]
Prelude> [10,9..1]
[10,9,8,7,6,5,4,3,2,1]
Prelude> [-5,-3..5]
[-5,-3,-1,1,3,5]
```
Now for some list comprehensions. The following examples show how to **draw down** from **ranges** in a list comprehension
```haskell
Prelude> [x*2 | x <- [1..5]]
[2,4,6,8,10]
Prelude> [x*x | x <- [1..10]]
[1,4,9,16,25,36,49,64,81,100]
```
You can add predicates to restrict the values of a list comprehension as follows
```haskell
Prelude> [x | x <- [1..10], odd x]
[1,3,5,7,9]
```
You can add more than one predicate. What are the even numbers between 1 and 50 that are divisible by 3?
```haskell
Prelude> [x|x<-[1..50], x `mod` 3==0, even x]
[6,12,18,24,30,36,42,48]
```
You can **draw down** from two variables as follows. Watch out for the order! Note that x\*\*y means _x to the power of y_
```haskell
Prelude> [x**y | x <- [1..5], y <- [2,3,4]]
[1.0,1.0,1.0,4.0,8.0,16.0,9.0,27.0,81.0,16.0,64.0,256.0,25.0,125.0,625.0]
Prelude> [x**y | y <- [2,3,4], x <- [1..5]]
[1.0,4.0,9.0,16.0,25.0,1.0,8.0,27.0,64.0,125.0,1.0,16.0,81.0,256.0,625.0]
```
# List Comprehension Exercise
Use list comprehensions to produce the following lists:
1. \[5,10,15,20,25,30,35,40,45,50,55,60\]
2. \[0.5,0.4,0.3,0.2,0.1,0\]
3. \[3,2,1,0,-1,-2,-3\]
4. \[1,8,27,64,125,216,343,512,729,1000\]
5. \[1,3,5,7,9\]
6. \[100,102,104,106,108,110,112,114,116,118,120\]
# Haskell and Lazy Evaluation
Haskell doesn't work things out until it has to - this is called lazy evaluation. This means you can write down things that might not lead to errors in imperative languages. For example
```haskell
take 5 [1..]
[1,2,3,4,5]
```
The above means take the first 5 elements from the infinite list that counts up from 1. Haskell only creates as much of the list as it needs. Combining lazy evaluation with functions that produce infinite lists means you can do such things as the following
```haskell
Prelude> take 10 (cycle [1,2])
[1,2,1,2,1,2,1,2,1,2]
Prelude> take 5 (repeat "Brubeck")
["Brubeck","Brubeck","Brubeck","Brubeck","Brubeck"]
```
# Summary
- Haskell allows you to use list comprehensions to work out lists of numbers.
- A list comprehension draws down from a range (e.g. x <- \[1..10\]) or a number of ranges.
- You can apply predicates (e.g. odd or even) to your list comprehension to decide what goes in it.
- List comprehensions allow you to solve problems in a completely different way to imperative programming languages. For example, here's how you'd find all the pythagorean triples (numbers such that a2 = b2+c2) for a,b,c <x.
```haskell
pythagTriples x = [(a, b, c) | a <-[1..x], b <- [1..x], c <- [1..x], c^2 == a^2 + b^2]
```
# Next
- [[More on Functions]]