2009/04/02

[The Little Schemer]rember

The Little Schemer」P.33 ~
3. Cons the Magnificent
  • magnificent
    • 壮大な
    • 堂々とした
    • 気高い
    • すばらしい
    • 飛び切り上等
今回のは「すばらしい」かな?わがんね。

  • The Second Commandment
    • Use cons to build lists.

(rember 'mint '(lamb chops and mint jelly))
;; => (lamb chops and jelly)
  • Rember
    • stands for remove a member.

(rember 'mint '(lamb chops and mint flavored mint jelly)
;; => (lamb shops and flavored mint jelly)
  • 最初のmintだけなくなってる

(rember 'toast '(bacon lettuce and tomato))
;; => (bacon lettuce and tomato)

(rember 'cup '(coffee  cup tea cup and hick cup))
;; => (coffee  tea cup and hick cup)
  • なくなったのは最初のcupだけ

自前のrember
(define rember
  (lambda (a lat)
    (cond ((null? lat) lat)
          ((eq? (car lat) a) (cdr lat))
          (else (cons (car lat) (rember a (cdr lat)))))))

(rember 'a '(a b c d))
;; => (b c d)

(rember 'b '(a b c d))
;; => (a c d)

(rember 'a '(a b c d a b c d))
;; => (b c d a b c d)

回答1:不完全なrember
(define rember
  (lambda (a lat)
    (cond
     ((null? lat) (quote ()))
     (else (cond
            ((eq? (car lat) a) (cdr lat))
            (else (rember a (cdr lat))))))))

(rember 'bacon '(bacon lettuce and tomato))
;; => (lettuce and tomato)

(rember 'and '(bacon lettuce and tomato))
;; => (tomato)
  • What did we do wrong?
    • We dropped "and", but we also lost all the atoms preceding "and".
  • How can we keep from losing the atoms "bacon" and "lettuce".
    • We use Cons the Magnificent. Remember cons, from chapter 1 ?

回答2
(define rember
  (lambda (a lat)
    (cond
     ((null? lat) (quote ()))
     (else (cond
            ((eq? (car lat) a) (cdr lat))
            (else (cons (car lat)
                        (rember a (cdr lat)))))))))

回答3:少し短くなってる
(define rember
  (lambda (a lat)
    (cond
     ((null? lat) (quote ()))
     ((eq? (car lat) a) (cdr lat))
     (else (cons (car lat)
                 (rember a (cdr lat)))))))

再度、自前
(define rember
  (lambda (a lat)
    (cond ((null? lat) lat)
          ((eq? (car lat) a) (cdr lat))
          (else (cons (car lat) (rember a (cdr lat)))))))
改行位置と、最初のnull?の戻り値が違う。

(rember 'sauce '(soy souce and tomato sauce)
;; => (soy and tomato sauce)

0 件のコメント:

コメントを投稿