全部博文(177)
分类: Python/Ruby
2011-07-19 10:18:08
11.5 Write a procedure initials that takes a sentence as its argument and returns a sentence of the first letters in each of the sentence's words:
> (initials '(if i needed someone)) (I I N S)11.6 Write a procedure countdown that works like this:
> (countdown 10) (10 9 8 7 6 5 4 3 2 1 BLASTOFF!) > (countdown 3) (3 2 1 BLASTOFF!)11.7 Write a procedure copies that takes a number and a word as arguments and returns a sentence containing that many copies of the given word:
> (copies 8 'spam) (SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM)12.1 Here is a definition of a procedure that returns the sum of the numbers in its argument sentence:
(define (addup nums) (if (empty? (bf nums)) (first nums) (+ (first nums) (addup (bf nums)))))Although this works, it could be simplified by changing the base case. Do that.
Answer:
12.2 Fix the bug in the following definition:
12.8 Write a procedure numbers that takes a sentence as its argument and returns another sentence containing only the numbers in the argument:
> (numbers '(76 trombones and 110 cornets)) (76 110)12.10 Write a procedure remove that takes a word and a sentence as arguments and returns the same sentence, but with all copies of the given word removed:
> (remove 'the '(the song love of the loved by the beatles)) (SONG LOVE OF LOVED BY BEATLES)12.13 Write a new version of the describe-time procedure from Exercise . Instead of returning a decimal number, it should behave like this:
> (describe-time 22222) (6 HOURS 10 MINUTES 22 SECONDS)Can you make the program smart about saying 1 CENTURY instead of 1 CENTURIES?
Answer:
(define (plural num wd)
(cond ((or (empty? wd) (empty? num)) "")
((or (= num 0) (= num 1)) (se num wd))
((> num 1) (se num (if (equal? wd 'century)
'centuries
(word wd 's))))
(else 'error)))
(define (unit n)
(item n '(second minute hour day week year century)))
(define (mod n)
(item n '(60 60 24 7 52 100 1)))
(define (plural num wd)
(cond ((or (empty? wd) (empty? num)) "")
((or (= num 0) (= num 1)) (se num wd))
((> num 1) (se num (if (equal? wd 'century)
'centuries
(word wd 's))))
(else 'error)))
(define (unit n)
(item n '(second minute hour day week year century "")))
(define (mod n)
(item n '(60 60 24 7 52 100)))
(define (describe-time nsec)
(define (iter n sec)
(cond ((and (= n 0) (= sec 0)) '(0 second)) ; 参数为0时
((or (= sec 0) (= n 8)) '()) ; 计算完毕
((= n 7) (plural sec (unit n))) ; Base case
(else (se (iter (+ n 1) (/ (- sec (modulo sec (mod n)))
(mod n)))
(plural (modulo sec (mod n)) (unit n))))))
(iter 1 nsec))
很显然,(describe-time 4967189641)的结果并不如题中所示。计算过程如下:
4967189641 sec = 82786494 min 1 sec
82786494 min = 1379774 hr 54 min
1379774 hr = 57490 d 14 hr
57490 d = 8212 w 6 d
8212 w = 157 y 48 w
157 y = 1 century 57 y
因此应该是(1 century 57 years 48 weeks 6 days 14 hours 54 minutes 1 second)
14.2
> (up 'town)