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