Programming in Haskell: Chapter 5 - List Comprehensions
Programming in Haskell: Chapter 5 - List Comprehensions
1
Set Comprehensions
{x2 | x {1...5}}
2
Lists Comprehensions
[x^2 | x [1..5]]
3
Note:
[(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)]
4
Changing the order of the generators changes
the order of the elements in the final list:
[(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)]
5
For example:
[(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)]
For example:
[1,2,3,4,5,6]
8
Guards
[x | x [1..10], even x]
For example:
> factors 15
[1,3,5,15]
10
A positive integer is prime if its only factors are 1
and itself. Hence, using factors we can define a
function that decides if a number is prime:
For example:
> prime 15
False
> prime 7
True
11
Using a guard we can now define a function that
returns the list of all primes up to a given limit:
For example:
> primes 40
[2,3,5,7,11,13,17,19,23,29,31,37]
12
The Zip Function
For example:
[(’a’,1),(’b’,2),(’c’,3)]
13
Using zip we can define a function returns the list
of all pairs of adjacent elements from a list:
For example:
[(1,2),(2,3),(3,4)]
14
Using pairs we can define a function that decides
if the elements in a list are sorted:
For example:
For example:
"abc" :: String
17
Because strings are just special kinds of lists, any
polymorphic function that operates on lists can
also be applied to strings. For example:
For example:
> pyths 5
[(3,4,5),(4,3,5)]
20
(2) A positive integer is perfect if it equals the sum
of all of its factors, excluding the number itself.
Using a list comprehension, define a function
[6,28,496]
21
(3) The scalar product of two lists of integers xs
and ys of length n is give by the sum of the
products of the corresponding integers:
n-1
(xsi * ysi )
i=0
22