我的SICP习题答案(2.17~2.23)

我的SICP习题答案(2.17~2.23)

2.17

(define (last-pair lst)
  (if (null? (cdr lst))
      (cons (car lst) ())
      (last-pair (cdr lst))))

2.18


(define (reverse lst)
  (define (iter lst-o lst-d)
    (if (null? lst-o)
        lst-d
        (iter (cdr lst-o) (cons (car lst-o) lst-d))))
  (iter lst null))

2.20

(define (same-parity x . lst)
  (define (filter lst ok?)
    (if (null? lst)
        ()
        (if (ok? (car lst))
            (cons (car lst) (filter (cdr lst) ok?))
            (filter (cdr lst) ok?))))
  (if (even? x)
      (cons x (filter lst (lambda(x) (= 0 (remainder x 2)))))
      (cons x (filter lst (lambda(x) (= 1 (remainder x 2)))))))

2.21

(define (square-list- items)
  (if (null? items)
      ()
      (cons (* (car items) (car items))
            (square-list- (cdr items)))))

(define (square-list items)
  (map (lambda(x) (* x x)) items))

2.22

第一种每次取出首元素平方后前插到新表,象reverse过程类似,所以是反的。
第二种只不过是把新表前插到元素前,得到的甚至不是一个list,而是
  ((((() . 1) . 4) . 9) . 16)

2.23

(define (for-each proc items)
  (if (not (null? items))
      ((lambda() (proc (car items))
       (for-each proc (cdr items))))))

你可能感兴趣的:(我的SICP习题答案(2.17~2.23))