序列操作举例
假设语言只提供
apply
:
Proc must be a procedure and args must be a list. Calls proc with the elements of the list
(append (list *arg1* ...) *args*)
as the actual arguments.
实现 map
单序列
(define (map p sequence)
((apply (lambda (a x)
(lambda (init)
(a (cons (p x) init))))
(lambda (x) x)
sequence) '()))
参考 复合数据-多米诺函数.
多序列
<待补充>
表长
(define (length seq)
(apply + 0
(map (lambda (x) 1)
seq)))
树叶(嵌套表元素数)
(define (count-leaves tree)
(define (map-func item)
(if (not (pair? item))
1
(count-leaves item)))
(apply + 0
(map map-func tree)))
这里使用了递归,缩小规模的代码在哪里?map
会让map-func
的处理对象从整个表变为其中的元素,这就缩小了规模,向原子元素(满足not pair
)靠拢。
积累
(define (accumulate op init seqs)
(define (add-to a x)
(if (not (pair? a))
(list (op a x))
(append a (op (pop a) x))))
(if (null? seqs)
init
(add-to (accumulate op init (cut-tail seqs))
(pop seqs))))
逆序
(define (reversed items)
(reduce (lambda (x y) (cons y x)) '() items))