序列操作举例

15 篇文章 0 订阅

序列操作举例


假设语言只提供 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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值