SICP section 2.2

2.17

;Exercise 2.17 (define (last-pair list) (let ((tail (cdr list))) (if (null? tail) list (last-pair tail)))) ;(last-pair (list 23 72 149 34)) ;(last-pair (list (list 1 2) (list 3 4))) 

2.18

;Exercise 2.18 (define (reverse list) (define (reverse-iter list result) (if (null? list) result (reverse-iter (cdr list) (cons (car list) result)))) (reverse-iter list '())) ;(reverse (list 1 4 9 16 25)) ;(car (reverse (list 1 4 9 16 25))) 

2.19

;Exercise 2.19 (define (cc amount coin-values) (cond ((= amount 0) 1) ((or (< amount 0) (no-more? coin-values)) 0) (else (+ (cc amount (except-first-denomination coin-values)) (cc (- amount (first-denomination coin-values)) coin-values))))) (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)) (define us-coins (list 50 25 10 5 1)) (define uk-coins (list 100 50 20 10 5 2 1 0.5)) ;(cc 100 us-coins)

2.20

;Exercise 2.20 (define (f x y . z) (+ x y (car z))) (define (same-parity . w) (define (same-parity-iter list rmd) (if (null? list) '() (if (= rmd (remainder (car list) 2)) (cons (car list) (same-parity-iter (cdr list) rmd)) (same-parity-iter (cdr list) rmd)))) (same-parity-iter w (remainder (car w) 2))) ;(same-parity 1 2 3 4 5 6 7) ;(same-parity 2 3 4 5 6 7)

2.36

;Exercise 2.36 ; (define (accumulate-n op init seqs) (if (null? (car seqs)) nil (cons (accumulate op init (first-of-subseqs seqs)) (accumulate-n op init (left-seqs seqs))))) ; (define (accumulate op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))) ; ;计算出由seqs每个元素的第一个元素构成的序列,例如: ; seqs = (list (list 1 2 3) (list 4 5 6)) ;(first-of-subseqs seqs) = (list 1 4) (define (first-of-subseqs seqs) (if (null? seqs) nil (cons (caar seqs) (first-of-subseqs (cdr seqs))))) ; ;和上一个相对,即除去子序列的第一个元素后剩下的,例如: ; seqs = (list (list 1 2 3) (list 4 5 6)) ;(first-of-subseqs seqs) = (list (list 2 3) (list 5 6)) (define (left-seqs seqs) (if (null? seqs) nil (cons (cdar seqs) (left-seqs (cdr seqs))))) ; ;test ;(define s (list (list 1 2 3) ; (list 4 5 6) ; (list 7 8 9) ; (list 10 11 12))) ; ;(accumulate-n + 0 s)

你可能感兴趣的:(list)