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
  • 相关阅读:
    ohmyzsh
    https://github.com/
    init 0,1,2,3,4,5,6
    关于反射
    docker学习笔记
    docker常见问题汇总
    ArrayList的sublist
    java-锁
    CAS-原子操作
    hashMap与concurrentHashMap
  • 原文地址:https://www.cnblogs.com/tclan126/p/6402954.html
Copyright © 2011-2022 走看看