YAY! Recursion (starting with lab9) Chapter 11 in Simply Scheme Recursion: - basically calling a procedure in itself. - EX: ; given a sentence of something, it returns the same argument. (define (something sent) (if (empty? sent) sent (se (first sent) (something (bf sent))))) - Tips: 1. When you get into an infinite loop, remember to check how you're calling your procedure inside the procedure. The argument to the procedure should be shorter than what you started with. -EX: ; Wrong (define (something sent) (if (empty? sent) sent (se (first sent) (something sent)))) <== this line 2. Check your parenthesis!!! Check if they are in the right position. 3. Think about the simplest cases that you can pass to your procedure. Questions: -What if your argument is an empty sentence or word? -What if there is only one element in your sentence? -What do you do if the first element doesn't fulfill your condition? 4. When you want to return a word or sentence or number, remember to use a constructor for the related return type. Also remember that your recursive procedure goes through each element one by one. For example, if your argument is a word, it will go through each letter. If your argument is a sentence, it will go through each word, one by one. So when you want to recurse, be sure to use a constructor (se, wd, +, -, ...). + and - are for NUMBERS ONLY. -EX: (define (something sent) (if (empty? sent) sent (se (first sent) (something (bf sent))))) <== this line Different things to do with recursion: 1. Changing/Doing something to each element in the sentence/word. - EX: ; given a sentence of numbers, adds 1 to each number inside. ; returns a sentence of numbers ; (+1to-all '(1 2 3 4 5)) should return (2 3 4 5 6) (define (+1to-all sent) (if (empty? sent) '() (se (+ 1 (first sent)) (+1to-all (bf sent))))) 2. Removing elements from the sentence/word. ; given a character and a word, ; remove every instances of the character from the word. ; return the word containing no instances of the character. (define (remove char wd) (cond ((empty? wd) wd) ((equal? char (first wd)) (remove char (bf wd))) (else (word (first wd) (remove char (bf wd)))))) 3. Aggregating or accumulating. Taking a sentence of things and returning a single value. ; takes a sentence of words or characters ; returns the argument as a single word. (define (make-word sent) (if (empty? sent) "" (word (first sent) (make-word (bf sent))))) ***** NOTE: Check how many arguments you use to call your procedure *****