


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



cons is the list constructor, whereas append glues two lists
Hugs> :t (:) (:) :: a -> [a] -> [a] Hugs
A slightly pathological case is x:⊥.
Hugs> :t (++) (++) :: [a] -> [a] -> [a] Hugs>
append glues lists on the right. cons can only add things to the left. [1, 2 , 3] + +[4] ; [1, 2 , 3 , 4] Remeber, append is defined as:
[] + +xs = xs (y : ys) + +xs = y : (ys + +xs)
[x] + +xs ; x : ([] + +xs) ; x : xs
Cons can be implemented using append but is less efficient. (x : xs) = [x] + +xs
We talked about the map function earlier
map f [] = [] map f (x : xs) = f x : (map f xs)
The following will not work as a definition since ”++” is not a constructor for lists. map f (xs + +ys) = (map f xs) + +(map f ys). Note::Pattern-matching works on patterns specified using data-type con- structors. snd (x:y:m) = y
sum [] = 0 sum (x : xs) = x + sum xs
prod [] = 0 prod (x : xs) = x ∗ prod xs
concat1 [] = []concat1 (xs + +xss) = xs + +concat xss
All these functions follow the following general pattern
f [] = e f (x : xs) = x ‘op‘ f xs
sum [1, 2 , 3] = 1 + sum [2, 3] = 1 + (2 + sum [3]) = 1 + (2 + (3 + sum [])) = 1 + (2 + (3 + 0))
prod[1, 2 , 3] = 1 ∗ (2 ∗ (3 ∗ 1))
concat[[1], [], [2, 3]] = [1] + +([] + +([2, 3] + +[]))
The pattern associates the ”‘op”’ to the right.
f oldr op e [] = e f oldr op e (x : xs) = x ‘op‘ (f oldr op x xs)
So if we had macros, we could just plug the functions and identity element in th macros to get the above definition.
If we want to do this in the normal way we have
all_pairs [] ys = [] all_pairs (x:xs) ys = (map ( y -> (x,y)) ys) ++ all_pairs xs ys
(map (\y → (1, y)) [′a′,′^ b′]) = ((\y → (1, y)) ′a′) : ( (\y → (1, y)) ′b′) : [] = (1,′^ a′) : ((1,′^ b′) : []) = [(1,′^ a′), (1,′^ b′)]
all pairs1 (x : xs) ys = map p ys + +all pairs 1 xs ys where p y = (x, y)
Main> [x*x| x <- [1..5], odd x] [1,9,25]
So what is list comprehension? {x ∈ S | P (x)} In set theory, this is definition by comprehension. In general, [e | Q] is a list comprehension
where e −is a Haskell expression Q −is a comma separated list of generations and guards
Generators look like x ← xs where x is a variable and xs is a list valued expression and a guard is a boolean valued expression. List comprehensions are very expressive but add no computational power. What is the semnatics? There are two rules :
[e | x ← xs, Q] = concat (map f x)where f x = [e | Q]
Note:: I had to leave early and so I missed last 5-7 mins. of lecture material.