[lisp] scheme学习2

本文介绍了Scheme语言中通过闭包实现的序对操作,并提供了一个计算列表长度和叶子节点数目的示例。此外,还详细解释了如何使用Honor规则来计算多项式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.在scheme中,为了效率,对序对的操作 cons car 和cdr是内部实现的,这里是scheme实现, 其中cons用到了闭包

 1 (define (cons a b)
 2     (define (dispatch m)
 3         (cond ((= m 1) a)
 4             ((= m 2) b)
 5             (else (error "index out of range")))
 6     )
 7     dispatch
 8 )
 9 
10 (define (car d) (d 1))
11 (define (cdr d) (d 2))

 2.计算列表长度和叶子节点数目

 1 (define (count_leaf x)
 2     (cond ((null? x) 0)
 3           ((not(pair? x)) 1)
 4           (else (+
 5             (count_leaf (car x))
 6             (count_leaf (cdr x))
 7             ))
 8           )
 9 )
10 
11 
12 (define (length items)
13     (define (length_iter count x)
14             (if (null? x)
15                 count
16                 (length_iter (+ 1 count) (cdr x))
17         )
18     )
19 
20     (length_iter 0 items)
21 )

 3.Honor规则计算多项式(SICP P80 2.34)

(define (accumulate op inital seq)
        (if (null? seq)
            inital
            (op (car seq) (accumulate op inital (cdr seq)))
            )
)


(define (honor_eval x coeff_seq)
        (accumulate
            (lambda (this_coeff highter_terms) 
                (
                    + this_coeff
                      (* x highter_terms)
                )
            )
            0
            coeff_seq
        )
)

 

转载于:https://www.cnblogs.com/fcyworld/p/7625278.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值