2. Pattern matching and basic types in Haskell
2.1. Pattern matching
It is likely that in the above implementations you used head
and tail
, or branch definitions combined with '_' to solve the exercises. Haskell supports a more elegant means of value introspection, called pattern matching. For instance, in:
f [] = ... f (h:t) = ...
(h:t)
is a pattern which denotes a non-empty list where h
is the first element and t
is the rest of the list. In fact, []
is also a pattern denoting the empty lists. Patterns are allways surrounded by round parentheses. They can also be composite, as in the exercise below:
2.1.1. Write a function which returns the number of elements from a list. Use patterns.
2.1.2. Write a function which takes a list of integer lists, and concatenates them. (E.g. f [ [1,2,3],[4,5] ] = [1,2,3,4,5]
).
2.1.3 (!) Write the same function, this time using only the cons (:
) operator as well as patterns.
2.1.4. Write a function which removes duplicates from a list of integers.
2.2. Types in Haskell
2.2.1. What are the types of x,y,z,w
and that of l
in the implementation below?
f (x:y:z:w:l) = w f _ = 0
How about:
f (x:y:z:w:l) = w
What is the difference?
2.2.2. What is the type of the function:
f x y = (x,y)
In the body of a function definition, ,
is a base constructor for pairs. The following are pairs: (1,2), (“Matei”,20), ([1,2],3)
. Note that there is no restriction on the type of the first and second values of a pair.
2.2.3. What is the type of the function:
f 'a' _ = [] f x y = x:y
In Haskell, the type String
is equivalent to [Char]
(hence strings are lists of chars). Strings can be introspected using patterns just like any other list.
2.2.4. Let f be the function below:
f "321CB" [("321CB", ["Matei", "Andrei", "Mihai"]), ("322CB",["George", "Matei"])] = ["Matei", "Mihai"]
What is the signature of f
?
2.3. Strings in Haskell
2.3.1. Write a function which takes a list of words and makes the first letter of each word uppercase.
2.3.2. Write a function which takes a list of words and makes all letters uppercase.
2.3.3. (!) Write a function which takes a text and a pattern and returns the number of occurrences of the pattern in the text. Example:
search "I eat green apples" "eat" = 1 search "ababaab" "aba" = 2
2.3.4. (!) What does f
, defined in exercise 2.2.4., do (note that Matei
and Mihai
both start with letter 'M')? Write an implementation for f
.
2.3.5. Write the signature and implement the following function:
f ["Matei", "Mihai"] ["Popovici","Dumitru"] = [("Matei","Popovici"), ("Mihai","Dumitru")]
2.3.6. Implement the following function:
f ["Matei", "Mihai"] ["Popovici","Dumitru"] = ["MPopovici", "MDumitru"]
2.3.7. Write a function which takes a list of pairs - student-name and grade, removes those with grades less than 5, splits the name in substrings, and adds one bonus point to people with three names. Example:
f [("Dan Matei Popovici",9),("Mihai",4),("Andrei Alex",6)] = [(["Dan", "Matei", "Popovici"],10),(["Andrei", "Alex"],6)]