CH 5
CH 5
PROGRAMMING IN HASKELL
In mathematics, the comprehension notation can
be used to construct new sets from old sets.
{x2 | x {1...5}}
0 1
In Haskell, a similar comprehension notation can z The expression x [1..5] is called a generator,
be used to construct new lists from old lists. as it states how to generate values for x.
2 3
[(1,4),(2,4),(3,4),(1,5),(2,5),(3,5)]
1
Dependant Generators Using a dependant generator we can define the
library function that concatenates a list of lists:
Later generators can depend on the variables that
are introduced by earlier generators. concat :: [[a]] [a]
concat xss = [x | xs xss, x xs]
For example:
A positive integer is prime if its only factors are 1 Using a guard we can now define a function that
and itself. Hence, using factors we can define a returns the list of all primes up to a given limit:
function that decides if a number is prime:
For example:
For example:
> prime 15
False
> primes 40
> prime 7
[2,3,5,7,11,13,17,19,23,29,31,37]
True
10 11
2
The Zip Function Using zip we can define a function returns the list
of all pairs of adjacent elements from a list:
A useful library function is zip, which maps two lists
to a list of pairs of their corresponding elements. pairs :: [a] [(a,a)]
pairs xs = zip xs (tail xs)
zip :: [a] [b] [(a,b)]
For example:
For example:
Using pairs we can define a function that decides Using zip we can define a function that returns the
if the elements in a list are sorted: list of all positions of a value in a list:
String Comprehensions Because strings are just special kinds of lists, any
polymorphic function that operates on lists can
also be applied to strings. For example:
A string is a sequence of characters enclosed in
double quotes. Internally, however, strings are
represented as lists of characters. > length "abcde"
5
16 17
3
Similarly, list comprehensions can also be used to Exercises
define functions on strings, such counting how
(1) A triple (x,y,z) of positive integers is called
many times a character occurs in a string:
pythagorean if x2 + y2 = z2. Using a list
comprehension, define a function
count :: Char String Int
count x xs = length [x’ | x’ xs, x == x’] pyths :: Int [(Int,Int,Int)]
(2) A positive integer is perfect if it equals the sum (3) The scalar product of two lists of integers xs
of all of its factors, excluding the number itself. and ys of length n is give by the sum of the
Using a list comprehension, define a function products of the corresponding integers: