This preview shows pages 1–2. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Lab 3: Pictures of Recursion CIS 252 i Introduction to Computer Science 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. Overview This lab will give you practice with writing recursive functions in Haskell, us ing the Pictures module ( http://www.cis.syr.edu/courses/cis252/code/ Pictures.hs ) from lecture. Remember to include the import Pictures directive at the top of your code. 2. Towards Recursion Consider the following function definitions (type them into Emacs and load them into the Ghci interpreter), each of which takes a picture as input and cre ates a row of pictures as output: picRow1 :: Picture > Picture picRow1 pic = pic picRow2 :: Picture > Picture picRow2 pic = sideBySide pic (picRow1 pic) picRow3 :: Picture > Picture picRow3 pic = sideBySide pic (picRow2 pic) picRow4 :: Picture > Picture picRow4 pic = sideBySide pic (picRow3 pic) The idea here is that, to create a row of two pictures, it suffices to combine (us ing the function sideBySide ) a picture with a row of 1 picture. To create a row of three pictures, one can combine a single picture with a row of two pictures. Likewise, we can combine a single picture with a row of three pictures to create a row of four pictures. In contrast, to create a row of one picture, there is no combining necessary: we can simply return the picture itself. More generally, for any positive number n > 1, we can create a row of n pictures by combining a single picture with a row of n 1 pictures. We implement this possibility with the following function, which accepts an extra argument that indicates how long to make the row: picRow :: Int > Picture > Picture picRow n pic  n == 1 = pic  n > 1 = sideBySide pic (picRow (n1) pic)  otherwise = error "picRow error: positive integer required" 3. Pieces of a Recursive Function In general, recursive functions have at least two separate cases: 1. The base case(s), which are the stopping cases The base cases are those cases where the function can return a value directly, without having to make additional recursive calls. In the case of picRow , the n == 1 case is a base case: when n = 1, picRow simply returns pic . 2. The recursive case(s) In the recursive cases, the function combines a partial answer with the result of a recursive call (i.e., a call to itself). In the case of picRow , the n > 1 cases are the recursive cases: in each case, picRow combines a single copy of pic with the result of the recursive call....
View
Full
Document
This note was uploaded on 02/19/2011 for the course CIS 325 taught by Professor Worden during the Spring '11 term at Syracuse.
 Spring '11
 worden
 Recursion

Click to edit the document details