方案-内存系统
我正在尝试制作一个存储系统,您可以在内存槽中输入一些内容。所以我正在做的是制作一个 Alist,成对的 car 是内存位置,cdr 是 val。我需要程序来理解两条消息:读和写。读取仅显示所选的内存位置以及分配给该位置的 val,写入会更改该位置或地址的 val。如何制作我的代码,以便它读取您想要的位置并写入您想要的位置?请自行测试一下。任何帮助将不胜感激。这就是我所拥有的:
(define make-memory
(lambda (n)
(letrec ((mem '())
(dump (display mem)))
(lambda ()
(if (= n 0)
(cons (cons n 0) mem) mem)
(cons (cons (- n 1) 0) mem))
(lambda (msg loc val)
(cond
((equal? msg 'read) (display
(cons n val))(set! n (- n 1)))
((equal? msg 'write) (set! mem
(cons val loc)) (set! n (- n 1)) (display mem)))))))
(define mymem (make-memory 100))
I am trying to make a memory system where you input something in a slot of memory. So what I am doing is making an Alist and the car of the pairs is the memory location and the cdr is the val. I need the program to understand two messages, Read and Write. Read just displaying the memory location selected and the val that is assigned to that location and write changes the val of the location or address. How do I make my code so it reads the location you want it to and write to the location you want it to? Feel free to test this yourself. Any help would be much appreciated. This is what I have:
(define make-memory
(lambda (n)
(letrec ((mem '())
(dump (display mem)))
(lambda ()
(if (= n 0)
(cons (cons n 0) mem) mem)
(cons (cons (- n 1) 0) mem))
(lambda (msg loc val)
(cond
((equal? msg 'read) (display
(cons n val))(set! n (- n 1)))
((equal? msg 'write) (set! mem
(cons val loc)) (set! n (- n 1)) (display mem)))))))
(define mymem (make-memory 100))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个可能的解决方案:
这具有不使用列表(为了速度)并防止恶意尝试访问预分配范围之外的内容的额外好处;)。
按预期工作:
如果您刚刚开始使用Scheme,这可能有点难以理解。
您可以在此处阅读有关
match-lambda
及其朋友的更多信息。向量相当于其他语言中的数组(阅读本文)。
A possible solution:
This has the added benefit of not using alists (for speed) and protecting against malicious attempts to access stuff outside the preallocated range ;).
Works as desired:
This might be a bit hard to grasp if you're just starting out with Scheme.
You can read more about
match-lambda
and friends here.Vectors are Scheme's equivalent of arrays in other languages (read this).