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))
然後就是把這兩個過程添加到求值表中即可:

(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




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章