zoukankan      html  css  js  c++  java
  • SICP_2.30-2.32

     1 #lang racket
     2 ;;;;;;;;;;;;;;;;;;;;;;2.30
     3 (define (square-tree tree)
     4   (cond ((null? tree) '())
     5         ((not (pair? tree)) (square tree))
     6         (else (cons (square-tree (car tree))
     7                     (square-tree (cdr tree))))))
     8 
     9 (define (square x)
    10   (* x x))
    11 
    12 (define (square-tree2 tree)
    13   (map (lambda (sub-tree)
    14          (if (pair? sub-tree)
    15              (square-tree2 sub-tree)
    16              (square sub-tree)))
    17        tree))
    18 
    19 ;;;;;;;;;;;test
    20 (square-tree (list 1 (list 2 (list 3 4) 5)
    21                    (list 6 7)))
    22 
    23 (square-tree2 (list 1 (list 2 (list 3 4) 5)
    24                    (list 6 7)))
    25 
    26 ;;;;;;;;;;;;;2.31
    27 (define (square-tree3 tree) (tree-map square tree))
    28 
    29 (define (tree-map proc tree)
    30   (map (lambda (sub-tree)
    31          (if (pair? sub-tree)
    32              (tree-map proc sub-tree)
    33              (proc sub-tree)))
    34        tree))
    35 
    36 (square-tree3 (list 1 (list 2 (list 3 4) 5)
    37                    (list 6 7)))
    38 
    39 ;;;;;;;;;;;;2.32
    40 (define (subsets s)
    41   (if (null? s)
    42       (list '())
    43       (let ((rest (subsets (cdr s))))
    44         (append rest (map (lambda (x) (cons (car s) x))
    45                           rest)))))
    46 
    47 (subsets (list 1 2 3))
    48 
    49 ;;;;;;;;;;;;;;;;参考解释:
    50 ;;;;;;;;subsets S = subsets S/e ∪ (e ∪ each subset of S/e)
    ;;;;;;;;;; 用替代模型
    ;(subsets '(1 2 3))
    ;rest ← (subsets '(2 3))
    ;       rest ← (subsets '(3))
    ;              rest ← (subsets '())
    ;                     '(())
    ;              (append '(()) (map ⟨…⟩ '(())))
    ;              '(() (3))
    ;       (append '(() (3)) (map ⟨…⟩ '(() (3))))
    ;       '(() (3) (2) (2 3))
    ;(append '(() (3) (2) (2 3)) (map ⟨…⟩ '(() (3) (2) (2 3))))
    ;'(() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3))

    在SICP这几节中加深对cons和list的理解的句子:

    1.nil的值表示序对的链结束,它也可以当做一个不包含任何元素的序列,空表。

    2.利用序对可以构造出的有用结构是序列——一批数据对象的有序汇集。

    3.在本书中我们用术语专指那些有表尾结束标记的序对的链。与此相对应,用术语表结构指所有由序对构造起来的数据结构,而不仅是表。

    4.cons可以用于构造表它在原有的表前面加上一个元素。

    图为(list (list 1 2) (list 3 4)) 和 (cons (list 1 2) (list 3 4))的区别

    Yosoro
  • 相关阅读:
    她又在这个星期联系我了 20110422
    用心去做 20110307
    2011年随笔记
    让我有勇气坚持下去 20110427
    2011年随笔记 5月30号以后的日志薄
    因为迷失,所以 201103015
    迷失只是暂时 20110313
    我们做一对好哥们吧 20101228
    3.20号,她恢复了联系 20110320
    FW: Deploy reporting services web parts (RSWebParts) to SharePoint 2010
  • 原文地址:https://www.cnblogs.com/tclan126/p/6402954.html
Copyright © 2011-2022 走看看