Recursion Problems

Here is one attempt to write the average procedure, which takes a sentence of numbers, adds them all up, and divides the total by the number of numbers in the sentence. It doesn't work. Figure out why.

(define (average sent)
  (if (= 1 (count sent)) ;;the average of a one-word sentence is the number
      (first sent)
      (/ (+ (first sent) (average (bf sent))) (count sent)) ;;otherwise, add them up and divide by the count of the sentence

Write a procedure called wheel-of-fortune. This is a lot like the hangman program you wrote earlier, but it works on whole sentences. It takes a word of letters that have been guessed and a sentence with the secret phrase people are trying to guess. It should replace all of the letters in the phrase that have not yet been guessed with *s. Use recursion. Don't use higher-order procedures.

Example: (wheel-of-fortune 'rstlne '(the second exam)) would give (t*e se**n* e***).


Modify the 1-extra? procedure that you wrote in lab to get 2-extra?. 1-extra? took two words and returned #t if the first word was the result of adding one extra letter to the second word and #f otherwise. 2-extra? should take two words and return #t if the first word is the result of adding two extra letters to the second word.

Examples:

  1. (1-extra? 'hat 'ht) => #t
  2. (1-extra? 'hat 'hi) => #f
  3. (2-extra? 'hat 'h) => #t
  4. (2-extra? 'clam 'am) => #t
  5. (2-extra? 'clam 'cm) => #t
  6. (2-extra? 'clam 'cla) => #f

Here is the code to 1-extra?.

(define (1-extra? wd1 wd2)
  (cond ((empty? wd1) #f)
        ((empty? wd2) (= (count wd1) 1))
        ((equal? (first wd1) (first wd2))
         (1-extra? (bf wd1) (bf wd2)))
        (else (equal? (bf wd1) wd2))))

Higher-Order Procedure Problems

I tried to write a procedure that squared every number in a sentence and added the squares up. This is pretty easy if you use every and accumulate, but I wanted to do it the hard way and only use accumulate. Here is the code I wrote:

(define (sum-of-squares sent)
  (accumulate (lambda (total new)
                (+ total (* new new)))
              sent))

Unfortunately, when I call (sum-of-squares '(1 2 3)), I get 122 instead of 14. Then I fix one bug and (sum-of-squares '(1 2 3)) returns 8. This is better, but still not correct.

Question: What did I fix to make it return 8?

Question: What else should I fix to make it return 14?


Write a procedure called wheel-of-fortune. This is a lot like the hangman program you wrote earlier, but it works on whole sentences. It takes a word of letters that have been guessed and a sentence with the secret phrase people are trying to guess. It should replace all of the letters in the phrase that have not yet been guessed with *s. Don't use recursion. Use higher-order procedures.

Example: (wheel-of-fortune 'rstlne '(the second exam)) would give (t*e se**n* e***).