码迷,mamicode.com
首页 > 其他好文 > 详细

[lisp] scheme学习2

时间:2017-10-04 14:24:58      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:规则   sicp   logs   val   else   def   efi   seq   eval   

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
        )
)

 

[lisp] scheme学习2

标签:规则   sicp   logs   val   else   def   efi   seq   eval   

原文地址:http://www.cnblogs.com/fcyworld/p/7625278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!