Docsity

Patterns for List Processing - Laboratory 5 | CIS 252, Lab Reports of Computer Science

Toggle sidebar
bg1
Lab 5: Patterns for List Processing
This lab gives you some practice with some common idioms for list processing.
These idioms—mapping,filtering, and folding— are so common that Haskell (and
most other functional programming languages) includes special functions that en-
capsulate them. We’ll cover those functions in class soon, but they are not the
focus of this lab.
This lab covers material discussed in Sections 7.4 and 9.1 of the textbook. You
may work singly or in pairs on this lab: If you work with a partner, turn
in a single solution with both names on it.
1 Mapping (Applying to All)
Last week’s lab focused on list comprehensions which provide a mechanism for
defining new lists out of old lists. For example, the following function accepts a
list of integers and doubles all of the elements in it:
doubleAll :: [Int] -> [Int]
doubleAll lst = [ 2*x | x <- lst]
This comprehension includes a generator x <- lst and a transformation 2*x.
Because the comprehension doesn’t include any tests to filter out elements, the
resulting list will always contain the same number of elements as the initial list.
Thus, for example, doubleAll [1,3,5,7,10] will return a five-element list.
Here is a version of doubleAll written using explicit recursion:
doubleAll [] = []
doubleAll (x:xs) = 2*x : doubleAll xs
The equation for the empty list is straightforward: doubling every element of
an empty list should result in another empty list. The second equation handles
nonempty lists and is explicit about how the new list is generated: we transform
the head of the list using the same transformation as in the list comprehension
(2*x), and we tack it on to the front of the list obtained by transforming the rest
of the list (via the recursive call). Each recursive call has the effect of generat-
ing the next element to be operated on; thus the recursive calls—along with the
binding of the function arguments to the pattern (x:xs)—play the role of the
generator x <- lst.
As another example, consider the following function (make sure you understand
what it does by trying it out on some test data):
addPairs :: [(Int,Int)] -> [[Int]]
addPairs pairList = [[m+n] | (m,n) <- pairList]
Here is a version of addPairs written using explicit recursion:
addPairs [] = []
addPairs ((m,n):rest) = [m+n] : addPairs rest
Once again, notice that the recursive definition uses exactly the same transfor-
mation as the list-comprehension version, and tacks (using the :operator) the
first-element result onto the result of the recursive call.
Note: Occasionally, you may find that you need to put parentheses around
the transformation portion of the recursive definition, due to operator prece-
dence. For example, a:b:list gets interpretted as a:(b:list); if you mean
(a:b):list, you must include the parentheses.
Finally, sometimes you’ll need to pass around an extra argument, if the func-
tion itself takes more than one argument. For example, consider the following
generalization of doubleAll:
multAll :: Int -> [Int] -> [Int]
multAll m lst = [ m*x | x <- lst]
The explicit-recursion version of this function must pass around the arguent mon
each call:
multAll m [] = []
multAll m (x:xs) = m*x : multAll m xs
2 Filtering (Element Selection)
We’ve seen in list comprehensions how one can filter out some of the elements
of the original list via adding tests to the list comprehension. For example, the
following function accepts a list of integers and doubles all the elements in it that
are less than 10 (it drops the rest):
doubleSome :: [Int] -> [Int]
doubleSome lst = [ 2*x | x <- lst, x < 10]
Here is a version of doubleSome written using explicit recursion:
CIS 252 (Spring 2009) — Introduction to Computer Science Page 1
pf3

Partial preview of the text

Download Patterns for List Processing - Laboratory 5 | CIS 252 and more Lab Reports Computer Science in PDF only on Docsity!

This lab gives you some practice with some common idioms for list processing. These idioms—mapping, filtering, and folding— are so common that Haskell (and most other functional programming languages) includes special functions that en- capsulate them. We’ll cover those functions in class soon, but they are not the focus of this lab.

This lab covers material discussed in Sections 7.4 and 9.1 of the textbook. You may work singly or in pairs on this lab: If you work with a partner, turn in a single solution with both names on it.

1 Mapping (Applying to All)

Last week’s lab focused on list comprehensions which provide a mechanism for defining new lists out of old lists. For example, the following function accepts a list of integers and doubles all of the elements in it:

doubleAll :: [Int] -> [Int] doubleAll lst = [ 2*x | x <- lst]

This comprehension includes a generator x <- lst and a transformation 2*x. Because the comprehension doesn’t include any tests to filter out elements, the resulting list will always contain the same number of elements as the initial list. Thus, for example, doubleAll [1,3,5,7,10] will return a five-element list.

Here is a version of doubleAll written using explicit recursion:

doubleAll [] = [] doubleAll (x:xs) = 2*x : doubleAll xs

The equation for the empty list is straightforward: doubling every element of an empty list should result in another empty list. The second equation handles nonempty lists and is explicit about how the new list is generated: we transform the head of the list using the same transformation as in the list comprehension (2*x), and we tack it on to the front of the list obtained by transforming the rest of the list (via the recursive call). Each recursive call has the effect of generat- ing the next element to be operated on; thus the recursive calls—along with the binding of the function arguments to the pattern (x:xs)—play the role of the generator x <- lst.

As another example, consider the following function (make sure you understand what it does by trying it out on some test data):

addPairs :: [(Int,Int)] -> [[Int]] addPairs pairList = [[m+n] | (m,n) <- pairList]

Here is a version of addPairs written using explicit recursion:

addPairs [] = [] addPairs ((m,n):rest) = [m+n] : addPairs rest

Once again, notice that the recursive definition uses exactly the same transfor- mation as the list-comprehension version, and tacks (using the : operator) the first-element result onto the result of the recursive call. Note: Occasionally, you may find that you need to put parentheses around the transformation portion of the recursive definition, due to operator prece- dence. For example, a:b:list gets interpretted as a:(b:list); if you mean (a:b):list, you must include the parentheses. Finally, sometimes you’ll need to pass around an extra argument, if the func- tion itself takes more than one argument. For example, consider the following generalization of doubleAll:

multAll :: Int -> [Int] -> [Int] multAll m lst = [ m*x | x <- lst]

The explicit-recursion version of this function must pass around the arguent m on each call:

multAll m [] = [] multAll m (x:xs) = m*x : multAll m xs

2 Filtering (Element Selection)

We’ve seen in list comprehensions how one can filter out some of the elements of the original list via adding tests to the list comprehension. For example, the following function accepts a list of integers and doubles all the elements in it that are less than 10 (it drops the rest):

doubleSome :: [Int] -> [Int] doubleSome lst = [ 2*x | x <- lst, x < 10]

Here is a version of doubleSome written using explicit recursion:

doubleSome [] = [] doubleSome (x:xs) | x < 10 = 2*x : doubleSome xs | otherwise = doubleSome xs

This function is similar to the recursive definition of doubleAll, except that we don’t always tack on the element 2x. Instead, we only tack on those elements 2x for which the test x < 10 is satisfied. Recursive calls still provide the mech- anism for “marching down” the list; at each point, we look at the first element of the list to determine whether to include its transformation in the final result.

Similarly, in Lab 4 we saw the function:

sampleFun :: [(Int,Int)] -> [[Int]] sampleFun pairList = [[m+n] | (m,n) <- pairList, n == 2*m]

Here is a version of sampleFun written using explicit recursion:

sampleFun [] = [] sampleFun ((m,n):rest) | n == 2*m = [m+n] : sampleFun rest | otherwise = sampleFun rest

3 Folding (Combining Results)

The list-comprehension notation is useful for converting lists into new lists, but it doesn’t provide a way to convert information in lists to a nonlist form. For example, a list comprehension won’t help in summing the elements of a list or in finding the maximum element in the list.

However, the same type of pattern we’ve seen in the explicit-recursion functions above can be used in this type of situation. The basic idea is that we can operate on individual elements of a list and combine that answer with the result obtained by a recursive call.

For example, consider the following function, which sums up the elements of a list of integers:

sumUp :: [Int] -> Int sumUp [] = 0 sumUp (x:xs) = x + sumUp xs

Note that this definition has a similar form to what we’ve seen already, except that it uses the operator + to combine the results, rather than the operator :. The other difference is that it no longer makes sense to return the empty list in the first equation, because sumUp needs to return an integer. You can also perform transformations on the individual elements of the list being processed. For example, the following function sums the squares of the elements of a list:

sumSquares :: [Int] -> Int sumSquares [] = 0 sumSquares (x:xs) = x*x + sumSquares xs

Finally, the following function concatenates all of the elements of a list of lists, to form a single list:

cat :: [[a]] -> [a] cat [] = [] cat (x:xs) = x ++ cat xs

For example, see what the value of cat [[1,2],[3,4],[],[6,7,8]] is. Here, the built-in append operator (++) is used to combine the results. Even though cat returns a list, the number of elements in that list bears no relation to the number of elements in the original list. Similarly, in the first equation, the two occurrences of [] play two different roles: it just happens to be the case that the result of catenating 0 lists is the empty list.

4 Your Problems

Important note: When filling in blanks below for list comprehensions, realize that blanks to the right of <- may or may not require tests. For example, the blank below might be filled in with “[1..5], even x” or simply with “[1..5]”:

[ x | x <- ]

  1. Use explicit recursion to write a function

prependAll :: String -> [String] -> [String]

such that (prependAll s ss) prepends each string in ss to the string s. For example,