CS-105 Solutions for practice homework set

Exercise 10.5
This procedure simply returns the sum of the squares of a and b. Note that + is used as the name for the procedure *, and * is used as the name for the procedure +.


Exercise 11.6

(define (countdown n)
  (if (= n 0)
      '(blastoff!)
      (se n (countdown (- n 1)))))


Exercise 11.7

(define (copies n wd)
  (if (= n 0)
      '()
      (se wd (copies (- n 1) wd))))


Exercise 12.1
Instead of testing whether nums has only length 1, we can check whether it has length 0:

(define (addup nums)
  (if (empty? nums)
      0
      (+ (first nums) (addup (bf nums)))))



Exercise 12.2
The base case returns the first element of the sentence, whereas it should return the first letter of the first element of the sentence:

(define (acronym sent)
  (if (= (count sent) 1)
      (first (first sent))
      (word (first (first sent))
	    (acronym (bf sent)))))


Note that the base case here can be simplified too:

(define (acronym sent)
  (if (= (count sent) 0)
      ""         ; returnning the empty word
      (word (first (first sent))
	    (acronym (bf sent)))))


Exercise 12.4
This procedure reverses its argument (which must be a sentence):

(define (f sent)
  (if (empty? sent)
      sent
      (se (f (bf sent)) (first sent))))


Exercise 12.10

(define (remove wd sent)
  (cond ((empty? sent) '())
	((equal? wd (first sent)) (remove wd (bf sent)))
	(else (se (first sent) (remove wd (bf sent))))))


Exercise 12.11

(define (count thing)
  (if (empty? thing)
      0
      (+ 1 (count (bf thing)))))


Exercise 12.13
Here is the version that works up to days, which you can extend.

(define (describe-time secs)
  (cond ((> secs 86400)
	 (se (quotient secs 86400)
	     'days
	     (describe-time (remainder secs 86400))))
	((> secs 3600)
	 (se (quotient secs 3600)
	     'hours
	     (describe-time (remainder secs 3600))))
        ((> secs 60)
	 (se (quotient secs 60)
	     'mins
	     (describe-time (remainder secs 60))))
        (else (se secs 'seconds))))


Behfar Bastani-Booshehri
Last modified: Fri Nov 6 13:46:11 CST 1998