This is an old revision of the document!
3. Recursive functions and tail-end recursion
3.1. Pattern matching revisited
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:
f [[1,2,3],[4,5]] = 1:(f [[2,3],[4,5]]) = 1:2:(f [[3],[4,5]]) = 1:2:3:(f [[],[4,5]]) = 1:2:3:(f [[4,5]]) = 1:2:3:4:(f [[5]]) = 1:2:3:4:5:(f [[]]) = 1:2:3:4:5:[]
3.1.4. Write a function which removes duplicates from a list of integers.
3.2. Tail-end recursive functions
3.2.1. Solve exercise 3.1.2. using a tail-recursive function.
3.2.2. Solve exercise 3.1.3. using a tail-recursive function.
3.2.3. Solve exercise 3.1.4. using a tail-recursive function.
3.2.4. 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]
.
3.3. Strings in Haskell revisited
In Haskell, strings are implemented as lists of type Char
. For instance 'a'
is a Char
. Also, the string “abc”
is the same as: 'a':'b':'c':[]
. Strings can be introspected (using pattern matching) and constructed exactly as any other list (using cons :
, ++
, etc.).
3.3.1. Write a tail recursive 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 tail recursive and non-tail-recursive functions which take 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. Do not use auxiliary functions. Example:
search "I eat green apples" "eat" = 1 search "ababaab" "aba" = 2