This is an old revision of the document!


3. Recursive functions and tail-end recursion

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:

3.1.1. Write a function which returns the number of elements from a list. Use patterns.

3.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]).

3.1.3 (!) Write the same function, this time using only the cons (:) operator as well as patterns. Hint:

[[1,2,3],[4,5]] =
1:[[2,3],[4,5]] =
1:2:[[3],[4,5]] =
1:2:3:[[],[4,5]] =
1:2:3:[[4,5]] =
1:2:3:4:[[5]] = 
1:2:3:4:5:[[]] =
1:2:3:4:5:[]

3.1.4. Write a function which removes duplicates from a list of integers.

3.2.1 Solve exercise 3.1.3. using a tail-recursive function.

3.2.2. Solve exercise 3.1.4. using a tail-recursive function.

3.2.3. Return all duplicates from a list, using a tail-recursive function. E.g., the duplicates from list [1,2,3,4,2,4,2,1] are [2,4,2,1].

In Haskell, strings are implemented as lists of type Char. For instance 'a' is a char

3.3.1. Write a function which takes a list of words and makes the first letter of each word uppercase. (Hint: google a respective function of chars).

3.3.2. Write a function which takes a list of words and makes all letters uppercase.

3.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

3.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.

3.3.5. Write the signature and implement the following function:

   f ["Matei", "Mihai"] ["Popovici","Dumitru"] = [("Matei","Popovici"), ("Mihai","Dumitru")]

3.3.6. Implement the following function:

   f ["Matei", "Mihai"] ["Popovici","Dumitru"] = ["MPopovici", "MDumitru"]

3.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)]