SICP Exercise 4.4


SICP Exercise 4.4
a)データガイドの方式が増えたほうが便利であるため、4.3に連絡する方式を引き続き採用する.
(define (eval-and exp env)
  (define (and-loop exps env)
    (if (null? exps)
        true
        (if (eval (car exps) env)
            (and-loop (cdr exps) env)
            false)))
  (and-loop (cdr exp) env))

(define (eval-or exp env)
  (define (or-loop exps env)
    (if (null? exps)
        false
        (if (eval (car exps) env)
            true
            (or-loop (cdr exps) env))))
  (or-loop (cdr exp) env))
次に、この2つのプロシージャを評価テーブルに追加します.
(put 'and eval-and)
(put 'or eval-or)
b)次に、andおよびorは、派生式によって実装される.
(define (and->if exp)
  (define (expand-clauses clauses)
    (if (null? clauses)
        true
        (let ((first (car clauses))
              (rest (cdr clauses)))
          (make-if first
                   (expand-clauses rest)
                   false))))
  (expand-clauses (cdr exp)))
(define (eval-and exp env)
  (eval (and->if exp) env))

(define (or->if exp)
  (define (expand-clauses clauses)
    (if (null? clauses)
        false
        (let ((first (car clauses))
              (rest (cdr clauses)))
          (make-if first
                   true
                   (expand-clauses rest)))))
  (expand-clauses (cdr exp)))
(define (eval-or exp env)
  (eval (or->if exp) env))
のテスト結果は以下の通りです.
;;; M-Eval input:
(and true true false)

;;; M-Eval value:
#f

;;; M-Eval input:
(or false true)

;;; M-Eval value:
#t