老潘已转到http://www.panxingzhi.net/。所有旧文章如有改动,此处将不再更新。谢谢。 I've moved to http://www.panxingzhi.net/. Updates on old posts are not applied here. Thanks.

SICP-2.5 solution

(define (cons x y)
  (* (expt 2 x) (expt 3 y)))

(define (keep-divide-until-remainder-not-zero remain count divisor predicate?)
  (if (predicate? remain)
      count
      (keep-divide-until-remainder-not-zero (/ remain divisor) (+ count 1) divisor predicate?)))

; when dividing by 2, we use odd? to determine if we may go on dividing
; false means we can go on
(define (car z)
  (keep-divide-until-remainder-not-zero z 0 2 odd?))

; when dividing by 3, we see if the remainder of the division is 0,
; to determine if we may go on dividing
; false means we can go on
(define (cdr z)
  (keep-divide-until-remainder-not-zero z 0 3
        (lambda (m) (if (eq? (remainder m 3) 0) #f #t))))

(define c (cons 5 6))
(car c)
(cdr c)

这题让我们内部用2^a3^b来储存a和b。之后我们用这个积能够被2或3连续整除的次数来得到a和b。





0 条评论:

添加评论