【SICP练习】109 练习3.22
2015-09-08 00:00
471 查看
练习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 ...)) <definitions of internal procedures> (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中不需要添加括号,否则会报错。感谢访问,希望对您有所帮助。 欢迎关注或收藏、评论或点赞。
为使本文得到斧正和提问,转载请注明出处:
http://blog.csdn.net/nomasp
版权声明:本文为 NoMasp柯于旺 原创文章,未经许可严禁转载!欢迎访问我的博客:http://blog.csdn.net/nomasp
相关文章推荐
- Ruby中使用Block、Proc、lambda实现闭包
- Ruby中的block、proc、lambda区别总结
- C++实现的一个可以写递归lambda的Y函数
- C#特性之匿名方法和Lambda表达式
- C#队列Queue用法实例分析
- 理解C#中的Lambda表达式
- 初步认识C#中的Lambda表达式和匿名方法
- C#3.0中Lambda表达式详解
- C#基础之Lambda表达式用法实例教程
- 用PHP写的基于Memcache的Queue实现代码
- ASP.NET State service状态服务的问题解决方法
- C#队列Queue多线程用法实例
- linux中编写自己的并发队列类(Queue 并发阻塞队列)
- vector,map,list,queue的区别详细解析
- Laravel 4.2 中队列服务(queue)使用感受
- 深入理解Java中的Lambda表达式
- Java8新特性之Lambda表达式浅析
- Java Lambda表达式详解和实例
- Java函数式编程(一):你好,Lambda表达式
- 用Python编写一个简单的Lisp解释器的教程