2.30

练习 2.30 请定义一个与练习2.21中square-list过程类似的square-tree过程。也就是说,它应该具有下面的行为:

(square-tree
    (list 1
        (list 2
            (list 3 4) 5)
                (list 6 7)))

(1 (4 (9 16) 25) (36 49))

请以两种方式定义square-tree,直接定义(即不使用任何高阶函数),以及使用map和递归定义。


第一种方式:

(define (square x) (* x x))

(define (square-tree tree) 
    (cond ((null? tree) '())
        ((null? (car tree)) '())
        ((pair? (car tree)) (cons (square-tree (car tree)) (square-tree (cdr tree))))
        (else (cons (square (car tree)) (square-tree (cdr tree))))
    )
)


(square-tree
    (list 1
        (list 2
            (list 3 4) 5)
                (list 6 7)))

第二种方式:

(define (square-2 x) 
    (if 
        (pair? x) 
        (cons (square-2 (car x)) (square-2 (cdr x)))
        (if (null? x)
            '()
            (* x x)
        )
    )
)

(define (square-tree-2 tree) 
    (map square-2 tree)
)

(square-tree-2
    (list 1
        (list 2
            (list 3 4) 5)
                (list 6 7)))

results matching ""

    No results matching ""