sicp-2.2.1
Posted on 2015-02-17 07:42:44 +0900 in SICP
2.17
(define (last-pair lst)
(let ([second (cdr lst)])
(if (null? second)
(car lst)
(last-pair second))))
2.18
(define (append list1 list2)
(if (null? list1)
list2
(cons (car list1) (append (cdr list1) list2))))
(define (reverse lst)
(if (null? lst)
lst
(append
(reverse (cdr lst))
(list (car lst)))))
2.19
(define us-coins (list 50 25 10 5 1))
(define uk-coins (list 100 50 20 10 5 2 1 0.5))
(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))
As this procedure does not rely not on the order, it would not affect the final answer.
2.20
(define (same-parity a . z)
(define (iter f left)
(if (null? left)
left
(let* ([first (car left)]
[second (cdr left)]
[temp (iter f second)])
(if (f first)
(cons first temp)
temp))))
(iter
(lambda (x) (= (remainder a 2) (remainder x 2)))
(cons a z)))
2.21
(define (square x) (* x x))
(define (square-list items)
(if (null? items)
null
(cons (square (car items))
(square-list (cdr items)))))
(define (square-list items)
(map square items))
2.22
(define (square-list items)
(define (iter things answer)
(if (null? things)
answer
(iter (cdr things)
(append answer
(list (square (car things)))))))
(iter items null))
The correct way is to use append
to add it into the last posision of the nested cons
.
2.23
(define (for-each proc items)
(cond
((null? items) #t)
(else (proc (car items))
(for-each proc (cdr items)))))
Hide Comments
comments powered by Disqus