关闭

2.2 层次闭包性质 练习 2.17 2.20

111人阅读 评论(0) 收藏 举报
分类:
#lang racket

(define a (list 1 2 3 4))

(define (list-ref items n)
  (if (= n 0)
      (car items)
      (list-ref (cdr items) (- n 1))))

#|
(define (length items)
  (if (null? items)
      0
      (+ 1 (length (cdr items)))))
|#

(define (length items)
  (define (iter items len)
    (if (null? items)
        len
        (iter (cdr items ) (+ 1 len))))
  (iter items 0))

;: (length a

;: 练习 2.17
;: 如果 items 本来为null? 应该报错
(define (last-pair items)
  (if (null? (cdr items))
      (car items)
      (last-pair (cdr items))))

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

;: 练习 2.18
(define (reverse items)
  (if (null? items)
      '()
      (append (reverse (cdr items))
              (list (car items)))))

;: 测试
(reverse (list 1 2 3 4))



;: 练习 2.19
;:

#| 原来的方式
(define (count-change amount)
  (cc amount 5))

(define (cc amount kinds-of-coins)
  (cond ((= amount 0) 1)
        ((or (< amount 0)
             (= kinds-of-coins 0))
         0)
        (else (+ (cc amount
                     (- kinds-of-coins 1))
                 (cc (- amount
                        (first-denomination kinds-of-coins))
                     kinds-of-coins)))))

(define (first-denomination kinds-of-coins)
  (cond ((= kinds-of-coins 1) 1)
        ((= kinds-of-coins 2) 5)
        ((= kinds-of-coins 3) 10)
        ((= kinds-of-coins 4) 25)
        ((= kinds-of-coins 5) 50)))

(count-change 100) => 292
|#

(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-vlaues)
  (cdr coin-vlaues))
(define (first-denomination coin-values)
  (car coin-values))

(cc 100 us-coins)
(display "*****************************")
(newline)


;: 练习 2.20
(define (filter check? items)
  (cond ((null? items) '())
        ((check? (car items))
         (cons (car items)
               (filter check? (cdr items))))
        (else
         (filter check? (cdr items)))))

;:::(filter odd? (list 1 2 3 4 5 6 7 8 9))

(define (same-parity first . items)
  (let ((check? (if (odd? first) odd? even?)))
    (cons first (filter check? items))))
;: 测试
(same-parity 1 2 3 4 5 6 7)
(same-parity   2 3 4 5 6 7)

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:8338次
    • 积分:729
    • 等级:
    • 排名:千里之外
    • 原创:35篇
    • 转载:7篇
    • 译文:27篇
    • 评论:0条