SICP習題解答2 17 2 23

2021-06-09 00:49:03 字數 2122 閱讀 5909

#lang racket

; exercise 2.17

(define (last-pair l)

(cond ((null? l) null)

((null? (cdr l)) l)

(else (last-pair (cdr l)))))

(last-pair (list 23 72 149 34))

(last-pair '(1))

(last-pair '())

; exercise 2.18

(define (reverse l)

(define (first-n-1 l)

(if (null? (cdr l))

null

(cons (car l) (first-n-1 (cdr l)))))

(if (null? l)

null

(cons (car (last-pair l)) (reverse (first-n-1 l)))))

(reverse (list 1 4 9 16 25)) ;; '(25 16 9 4 1)

; 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? l)

(null? l))

(define (except-first-denomination l)

(cdr l))

(define (first-denomination l)

(car l))

(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) ;; 292

;(cc 100 uk-coins) ;; 104561

;; coins-value的排列不會影響cc的結果

; exercise 2.20

(define (same-parity x . y)

(define (sp x y)

(define (odd? n) (= (remainder n 2) 1))

(cond ((null? y) null)

((odd? (+ x (car y))) (sp x (cdr y)))

(else (cons (car y) (sp x (cdr y))))))

(cons x (sp x y)))

(same-parity 1 2 3 4 5 6 7)

(same-parity 2 3 4 5 6 7)

; exercise 2.21

(define (square-list items)

(if (null? items)

null

(cons (square (car items)) (square-list (cdr items)))))

(define (square-list2 items)

(map square items))

(define (square x) (* x x))

(square-list (list 1 2 3 4))

(square-list2 (list 1 2 3 4))

; exercise 2.23

(define (for-each proc l)

(cond ((not (null? l))

(proc (car l))

(for-each proc (cdr l)))))

(for-each (lambda (x) (newline) (display x))

(list 57 321 88))

SICP習題解答1 1 1 8

lang racket exercise 1.1 10 5 3 4 9 1 6 2 2 4 4 6 define a 3 define b a 1 a b a b a b if and b a b a b ba cond a 4 6 b 4 6 7 a else 25 2 if b a b a co...

SICP習題解答2 7 2 16

lang racket exercise 2.7 define make interval a b cons a b define upper bound interval max car interval cdr interval define lower bound interval min c...

SICP習題1 6的解答

sicp就是名著 structure and interpretation of computer programs 著名的巫師書 wizard book 和紫書 purple book 雖說英文原版可以從網上合法 中文版翻譯也還不錯。閒話少敘,下面我們研究一下書中 1.1.7節的練習題1.6。原題...