FOOP Practice Midterm 3 -- Recursion & Lists Practice Problems

1.  What is the exact output of each:

> (cons '(yes you will) '(enjoy winter break))

 

> (append '(yes you will) '(enjoy winter break))

 

; This one is really important to understand. If you have questions, ask!
> (filter (lambda (x) (member? 'a x)) '((yeah) gunn should (have a) second turkey feast))



> (reduce append '((cows on) (toothpicks are) (delicious)))

 

> (define (mystery p? s)
    (cond ((empty? s) ‘())
          ((p? (first s)) (se (first s) (mystery p? (bf s))))
          (else (mystery p? (bf s))))) 
 
> (mystery number? '(one 2 three 4 5 six))

 

 

> (define (f n)
    (cond ((< n 3) 1)
          (else (+ (f (- n 1)) (f (- n 2))))))
 
> (f 5)

 

 

2. If Mr. Bell could cut his consumption of caffeinated products, it would improve his health. Despite being a math teacher, the only time he uses numbers in sentences is when he discusses his eating habits. Help Mr.Bell by writing the decaffeinate function, which takes a sentence uttered by Mr. Bell and chops the amount of caffeinated foods in half. You can write a helper function if you wish, but the decaffeinate function MUST be written recursively.

> (decaffeinate '(demand 4 chocolate bars and 16 bottles of Coke))
(demand 2 chocolate bars and 8 bottles of Mexican Coke)
 
> (decaffeinate '(drink 7 cups of tea))
(drink 3.5 cups of tea)

 

 

 

 

3. Write the function reversi that takes a sentence of words and returns a sentence containing the reverses of the words in reverse order. It also can take a word as its input and return the word in reverse order.

> (reversi '()) 
() 
 
> (reversi 'bautista) 
atsituab 
 
> (reversi '(alpha beta gamma)) 
(ammag ateb ahpla) 

 

Fill in the blanks to create reversi:

(define (reversi input)     
        (cond ((empty? input) ________________)        
              ((sentence? input) ________________________________________________)           
              (else ________________________________________________)))

 

 

4. The function rest-of-word takes a letter and a word as its arguments and returns the rest of the word, starting with the first instance of the letter. If the letter does not appear in the word, rest-of-words returns #f.

> (rest-of-word 'a 'hippogriff)
#f 
 
> (rest-of-word 'f 'inflammable) 
flammable 
 
> (rest-of-word 'a 'fairway) 
airway

 

 

 

5.  Write a procedure called deep-count that counts the number of words in a list

> (deep-count ‘(the (4 fish) swam through the seaweed (in the (kelp forest))))
11