博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【SICP练习】109 练习3.22
阅读量:7228 次
发布时间:2019-06-29

本文共 1900 字,大约阅读时间需要 6 分钟。

练习3-22

原文

Exercise 3.22. Instead of representing a queue as a pair of pointers, we can build a queue as a procedure with local state. The local state will consist of pointers to the beginning and the end of an ordinary list.

Thus, the make-queue procedure will have the form

(define (make-queue)   (let ((front-ptr ...)              (rear-ptr ...))        
(define (dispatch m) ...) dispatch))

Complete the definition of make-queue and provide implementations of the queue operations using this representation.

分析

这道题中的局部状态由指向一个常规表的开始和结束指针组成。并且要将insert-queue!和delete-queue!嵌套进整个过程中。通过dispatch来调用这些函数。

(define (make-queue)    (let ((front-ptr '())          (rear-ptr '()))   (define (empty-queue?)      (null? front-ptr))   (define (insert-queue! item)       (cond ((empty-queue?) (let ((init-list (list item))) (set! front-ptr init-list) (set! rear-ptr init-list) front-ptr))             (else (let ((new-item (list item))) (set-cdr! rear-ptr new-item) (set! rear-ptr new-item) front-ptr))))   (define (delete-queue!)       (cond ((empty-queue?) (error "DELETE! called with an empty queue" queue))             (else (set! front-ptr (cdr front-ptr)) front-ptr)))   (define (dispatch m)      (cond ((eq? m 'insert-queue!) insert-queue!)            ((eq? m 'delete-queue!) (delete-queue!))            ((eq? m 'empty-queue?) (empty-queue?))            (else (error "Unknown operation -- DISPATCH" m))))    dispatch))

测试

(define q3 (make-queue))        ;Value: q3((q3 'insert-queue!) 'a)                ;Value 15: (a)((q3 'insert-queue!) 'b);Value 16: (a b)(q3 'delete-queue!)                  ;Value 17: (b)(q3 'delete-queue!);Value: ()(q3 'empty-queue?)                   ;Value: #t

补充

由于insert-queue!有参数,所以在dispatch中不需要添加括号,否则会报错。



感谢访问,希望对您有所帮助。 欢迎关注或收藏、评论或点赞。


为使本文得到斧正和提问,转载请注明出处:


版权声明:本文为 NoMasp柯于旺 原创文章,如需转载请联系本人。

转载于:https://www.cnblogs.com/NoMasp/p/4786096.html

你可能感兴趣的文章
ros 安装教程
查看>>
使用charles抓包https,配置了证书,还是乱码的解决方案
查看>>
Javascript的this用法
查看>>
解决nginx 504 Gateway Time-out的一些方法
查看>>
SQL游标循环执行(又遇到了,记录一下吧)
查看>>
jQuery上注册函数的方法
查看>>
不要将@Autowired注解用于static方法
查看>>
关于达内培训的名企定制班
查看>>
Routing with restify and socket.io in node
查看>>
立体测距
查看>>
关于离线下载的一些免费的网站
查看>>
开发netfilter的一些坑
查看>>
java中map的clear和new性能对比
查看>>
macbook 备份系统
查看>>
klish 安装与使用
查看>>
Django实战(18):提交订单
查看>>
PHP时间戳函数总结
查看>>
开发自定义JSF组件(1) HelloWorld
查看>>
设计模式学习——策略模式:模拟鸭子应用
查看>>
lucene4.7 分词器(三)
查看>>