[lisp] scheme学习2
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 ) )