SICP: 第二章之序列操作:程序的共性

 

#lang racket

;guo lv qi
(define (filter predicate sequence)
  (cond ((null? sequence) '())
    ((predicate (car sequence))
     (cons (car sequence)
           (filter predicate (cdr sequence))))
    (else (filter predicate (cdr sequence)));else
    );cond
  );filter

(define (accumulate op initial sequence)
  (if (null? sequence)
      initial
      (op (car sequence)
      (accumulate op initial (cdr sequence))));if
  );accumulate

;mei ju int low~high
(define (enumerate-interval low high)
  (if (> low high)
      '()
      (cons low (enumerate-interval (+ low 1) high)))
  );enumerlate-interval

;mei ju tree's leaf
(define (enumerate-tree-leaf tree)
  (cond ((null? tree) '())
    ((not (pair? tree)) (list tree))
    (else (append (enumerate-tree-leaf (car tree))
              (enumerate-tree-leaf (cdr tree)))));cond
  );enumerate-tree-leaf

;append
(define (append lst1 lst2)
  (if (null? lst1)
      lst2
      (cons (car lst1) (append (cdr lst1) lst2)));if
  );append

;(enumerate-tree-leaf (list 1 (list 2 (list 3 4)) 5))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (sum-odd-squares tree)
  (accumulate + 
          0 
          (map (lambda (x)(* x x))
           (filter odd?
              (enumerate-tree-leaf tree));flter
           );map
          );accumulate
  );sum-odd-squares

(define (odd? a)
  (= 1 (remainder a 2))
  );odd?

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (even-fibs n)
  (accumulate cons
         '()
         (filter (lambda(x) (not (odd? x)))
             (map fib
              (enumerate-interval 0 n)));filter
   );accumulate
  );even-fib

(define (fib n)
  (define (fib-iter a b count)
    (if (= count 0)
    a
    (fib-iter b (+ a b) (- count 1))
     );if
    );fib-iter
  (fib-iter 0 1 n)
  );fib

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(define (list-fib-square n)
  (accumulate cons
          '()
          (map (lambda (x) (* x x))
           (map fib
            (enumerate-interval 0 n))));accumulate
  );list-fib-square

(define tree (list 1 (list 2 (list 3 4))))
(sum-odd-squares tree)

(even-fibs 10)

(list-fib-square 10)

 

posted on 2015-04-20 21:52  Zachary_wiz  阅读(303)  评论(0编辑  收藏  举报

导航