1 ]=> (list 1 (list 2 (list 3 4)))
;Value 9: (1 (2 (3 4)))
Sunday, June 7, 2009
Ex-2.23
(define (for-each proc l)
(if (not (null? l))
(begin (proc (car l))
(for-each proc (cdr l)))))
Ex-2.22
Why reverse order is obtained?
Let us see the execution of iter...
(iter '(1 2 3 4) '())
(iter '(2 3 4) '(1))
(iter '(3 4) '(4 1))
(iter '(4) '(9 4 1))
(iter '() '(16 9 4 1))
'(16 9 4 1)
After trying to "fix" here is what the execution of iter looks like..
(iter '(1 2) '())
(iter '(2) (cons '() 1))
(iter '() (cons (cons '() 1) 4))
(cons (cons '() 1) 4) => this is not (list 1 4)
Let us see the execution of iter...
(iter '(1 2 3 4) '())
(iter '(2 3 4) '(1))
(iter '(3 4) '(4 1))
(iter '(4) '(9 4 1))
(iter '() '(16 9 4 1))
'(16 9 4 1)
After trying to "fix" here is what the execution of iter looks like..
(iter '(1 2) '())
(iter '(2) (cons '() 1))
(iter '() (cons (cons '() 1) 4))
(cons (cons '() 1) 4) => this is not (list 1 4)
Ex-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))
Ex-2.20
(define (same-parity x . r)
(let ((proc (if (even? x) even? odd?)))
(cons x
(filter proc r))))
Ex-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 (first-denomination coins)
(car coins))
(define (no-more? coin-values)
(= (length coin-values) 0))
(define (except-first-denomination coin-values)
(cdr coin-values))
Order of coin-values doesn't affect the answer produced, because in the cc we're treating coin-values as just a set of values without any assumption of its order.
Ex-2.18
(define (reverse l)
(define (iter a r)
(if (null? a) r
(iter (cdr a) (cons (car a) r))))
(iter l '()))
Subscribe to:
Posts (Atom)
