SICP学习笔记 2.2.1 序列的表示

    练习2.17

;; 直接利用已经实现的list-ref和length过程即可
(define (last-pair items)
  (if (null? items)
      (display "null")
      (list-ref items (- (length items) 1))))

 

    练习2.18

;; 翻转即为将列表第二个元素翻转再加上第一个元素
(define (reverse items)
  (if (null? items)
      '()
      (append (reverse (cdr items)) (list (car items)))))
;; 翻转即为倒序取列表值再组合成新的列表
(define (reverse items)
  (define (reverse-iter a n)
    (if (< n 0)
	      '()
	      (cons (list-ref a n) (reverse-iter a (- n 1)))))
  (reverse-iter items (- (length items) 1)))

 

    练习2.19

(define (no-more? coin-values)
  (null? coin-values))

(define (except-first-denomination coin-values)
  (cdr coin-values))

(define (first-denomination coin-values)
  (car coin-values))
  
1 ]=> (cc 100 us-coins)
;Value: 292

1 ]=> (cc 100 (reverse us-coins))
;Value: 292

;; 改变coin-values的顺序不会影响结果
;; 因为在cc过程中递归的累加 只用某种币值的兑换种数和除去这种币值后的兑换种数, 因此和次数无关

 

    练习2.20

;; 首先定义flag过程, 以判断传入的两个数是否奇偶性一致
;; 然后在get-list过程中递归使用cdr取列表的剩余部分完成奇偶性检查
;; 最后将参数拼接成列表调用get-list过程
(define (same-parity x . y)
  (define (flag a b)
    (= (remainder a 2) (remainder b 2)))
  (define (get-list items)
      (if (null? items)
	        '()
      	  (if (flag x (car items))
      	      (cons (car items) (get-list (cdr items)))
      	      (get-list (cdr items)))))
  (get-list (cons x y)))
  
1 ]=> (same-parity 1 2 3 4 5 6 7)
;Value : (1 3 5 7)

1 ]=> (same-parity 2 3 4 5 6 7)
;Value : (2 4 6)

1 ]=> (same-parity 2 2 0 128 6 7)
;Value : (2 2 0 128 6)
 

    练习2.21

(define (square-list items)
  (if (null? items)
      '()
      (cons (square (car items))
	    (square-list (cdr items)))))
	    
(define (square-list items)
  (map (lambda (x) (square x)) items)) 

 

    练习2.22

;; Louis在组成新的结果时, 在cons的两个参数上搞反了
;; 调整之后因为对列表和数值直接结合导致出现如下结果
;Value : (((((() . 1) . 4) . 9) . 16) . 25)

;; 因此做如下修正, 将数值变换为列表然后再和之前的结果相加
(define (square-list items)
  (define (iter things answer)
    (if (null? things)
	      answer
	      (iter (cdr things)
	            (append answer
		                  (list (square (car things)))))))
  (iter items '()))
 

    练习2.23

(define (for-each proc items)
  (if (null? items)
      '()
      (and (proc (car items))
	      (for-each proc (cdr items))))) 
 
展开阅读全文

没有更多推荐了,返回首页