Lisp学习笔记(三)

高阶函数抽象

高阶过程以过程作为参数,或者以过程作为返回值。
试想对于求和公式:f(a)+....f(b),如何描述她的过程呢?求和的模板是下面的描述:

(define (<name> a b)
    (if (> a b) 0
        (+ (<term> a) (<name> (next a) b))
    )
)

上面的代码中,term就是求和公式中的f,next则是求和参数的变化过程。我们将上面的过程翻译成lisp:

(define (sum term a next b)
    (if (> a b) 0 (+ (term a) (sum term (next a) next b)))
)

上面是一个递归过程,我们还可以写成迭代过程:

(define (sum term a next b)
    (define (iter a result)
        (if (> a b) result
            (iter (next a) (+ result (term a)))
        )
    )
    (iter a 0)
)

举个具体的例子,加入我们要计算1+2+3+...+50,代码如下所示:

(define (inc x)
    (+ x 1)
)
(define (self x)
    x
)
(sum self 1 inc 50)

累加过程是可以用高阶过程表示的大量类似抽象中最简单的一个。下面我们写一个类似的product过程,它返回给定范围内各点的某个函数值的乘积。

(define (product term a next b)
    (if (> a b) 1
        (* (term a) (product term (next a) next b))
    )
)
(define (iterProduct term a next b)
    (define (iter a result)
        (if (> a b) result
            (iter (next a) (* result (term a)))
        )
    )
    (iter a 1)
)

前者是递归过程,后者是相应的迭代过程。我们可以用它来实现前面的factorial过程:

(define (self x) x)
(define (inc x) (+ x 1))
(product self 1 inc 5)

上面计算的是5!.

以上的累加和累积过程,我们可以对其进行更高一阶的抽象:

(define (accumulate combiner null-value term a next b)
  (if (> a b) null-value
      (combiner (term a) (accumulate combiner null-value term (next a) next b))
  )

(define (iterAccumulate combiner null-value term a next b)
    (define (iter a result)
      (if (> a b) result
          (iter (next a) (combiner result (term a))))
    )
    (iter a null-value)
  )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值