【SICP练习】148 练习4.4

本文介绍了如何在解释器中实现逻辑操作符and与or的特殊形式。通过定义适当的语法过程和评估过程,实现了这两个逻辑操作符的功能。此外,还提供了具体的代码实现,包括如何将and与or表达式转换为相应的if表达式。

练习4-4

原文

Exercise 4.4. Recall the definitions of the special forms and and or from chapter 1:

● and: The expressions are evaluated from left to right. If any expression evaluates to false, false is returned; any remaining expressions are not evaluated. If all the expressions evaluate to true values, the value of the last expression is returned. If there are no expressions then true is returned.

● or: The expressions are evaluated from left to right. If any expression evaluates to a true value, that value is returned; any remaining expressions are not evaluated. If all expressions evaluate to false, or if there are no expressions, then false is returned.

Install and and or as new special forms for the evaluator by defining appropriate syntax procedures and evaluation procedures eval-and and eval-or. Alternatively, show how to implement and and or as derived expressions.

代码

 ((and? expr) (evaln (and->if expr) env)) 

 (define (and->if expr) 
         (expand-and-clauses (and-clauses expr))) 
 (define (expand-and-clauses clauses) 
         (if (null? clauses) 
             (make-if 'true 'true 'false)         
                 (let ((first (car clauses)) 
                           (rest (cdr clauses))) 
                    (if (null? rest)  
                            (make-if first first 'false) 
                        (make-if first (expand-and-clauses rest) 'false))))) 

 ((or? expr) (evaln (or->if expr) env))  
 (define (or->if expr) 
         (expand-or-clauses (or-clauses expr))) 
 (define (expand-or-clauses clauses) 
         (if (null? clauses) 
             (make-if 'true 'false 'true) 
                 (let ((first (car clauses)) 
                           (rest (cdr clauses))) 
                  (make-if first 'true (expand-or-clauses rest))))) 



感谢您的访问,希望对您有所帮助。

欢迎大家关注或收藏、评论或点赞。


为使本文得到斧正和提问,转载请注明出处:
http://blog.youkuaiyun.com/nomasp


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值