CG@CPPBLOG

/*=========================================*/
随笔 - 76, 文章 - 39, 评论 - 137, 引用 - 0
数据加载中……

我的SICP习题答案(2.17~2.23)

2.17

(define (last-pair lst)
  (if (null? (cdr lst))
      (cons (car lst) ())
      (last-pair (cdr lst))))

2.18


(define (reverse lst)
  (define (iter lst-o lst-d)
    (if (null? lst-o)
        lst-d
        (iter (cdr lst-o) (cons (car lst-o) lst-d))))
  (iter lst null))

2.20

(define (same-parity x . lst)
  (define (filter lst ok?)
    (if (null? lst)
        ()
        (if (ok? (car lst))
            (cons (car lst) (filter (cdr lst) ok?))
            (filter (cdr lst) ok?))))
  (if (even? x)
      (cons x (filter lst (lambda(x) (= 0 (remainder x 2)))))
      (cons x (filter lst (lambda(x) (= 1 (remainder x 2)))))))

2.21

(define (square-list- items)
  (if (null? items)
      ()
      (cons (* (car items) (car items))
            (square-list- (cdr items)))))

(define (square-list items)
  (map (lambda(x) (* x x)) items))

2.22

第一种每次取出首元素平方后前插到新表,象reverse过程类似,所以是反的。
第二种只不过是把新表前插到元素前,得到的甚至不是一个list,而是
  ((((() . 1) . 4) . 9) . 16)

2.23

(define (for-each proc items)
  (if (not (null? items))
      ((lambda() (proc (car items))
       (for-each proc (cdr items))))))

posted on 2008-06-11 22:56 cuigang 阅读(850) 评论(2)  编辑 收藏 引用 所属分类: Lisp/Scheme我的SICP答案

评论

# re: 我的SICP习题答案(2.17~2.23)  回复  更多评论   

2.17有个错误
(define (last-pair lst)
(if (null? (cdr lst))
(cons (car lst) ())
(last-pair (cdr lst))))
()改为'()
2009-01-25 11:12 | soma

# re: 我的SICP习题答案(2.17~2.23)  回复  更多评论   

(define (same-parity x . lst)
(define (filter lst ok?)
(if (null? lst)
()
(if (ok? (car lst))
(cons (car lst) (filter (cdr lst) ok?))
(filter (cdr lst) ok?))))
(if (even? x)
(cons x (filter lst (lambda(x) (= 0 (remainder x 2)))))
(cons x (filter lst (lambda(x) (= 1 (remainder x 2)))))))

我尝试着用简单的递归办法:

(define (same-parity? x y)
(or (and (even? x) (even? y))
(and (odd? x) (odd? y))))

(define (same-parity x . y)
(cond ((null? y) '())
((same-parity? x (car y)) (cons (car y) (same-parity x (cdr y))))
(else (same-parity x (cdr y)))))

(same-parity 1 2 3 4 5 6 7)

然而在做调用(same-parity x (cdr y)) 时出错了,问题是参数表把(cdr y)这个表当作参数表的第一个值,即((2 3 4 5 6 7)), 有什么办法可以解决这个问题么?
2009-02-09 18:33 | mabusyao

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理