2.33

练习 2.33 请填充下面缺失的表达式,完成将一些基本的表操作看作累积的定义:

(define (map p sequence)
    (accumulate (lambda (x y) <??>) nil sequence)
)

(define (append seq1 seq2)
    (accumulate cons <??> <??>)
)

(define (length sequence)
    (accumulate <??> 0 sequence)
)

首先,定义 accumulate

(define (accumulate op initial sequence)
    (if (null? sequence)
        initial
        (op (car sequence)
            (accumulate op initial (cdr sequence))) 
    )
)
(define (map p sequence)
    (accumulate (lambda (x y) (cons (p x) y)) '() sequence)
)

(map (lambda (x) (+ x 1)) (list 1 2 3 4))
(define (append seq1 seq2)
    (accumulate cons seq2 seq1) 
)

(append (list 1 2) (list 3 4))
(define (length sequence)
    (accumulate (lambda (x y) (+ 1 y)) 0 sequence)
) 

(length (list 1 2 3 4 5))

results matching ""

    No results matching ""