方案R5RS:按引用传递
我正在尝试模拟方案中的堆栈。我正在使用 DrScheme,并选择语言 R5RS。我需要创建弹出、推送和查看的函数。但我无法弄清楚如何通过引用传递。我读过一些有关盒子的信息,但 R5RS 不支持它们。还有其他方法可以通过引用传递吗?
I'm trying to emulate a stack in scheme. I'm using DrScheme and I select the language R5RS. I need to create functions that pop, push, and peek. But i'm having trouble figuring out how to pass by reference. I've read some information about boxes, but they are not supported in R5RS. Is there any other way to pass by reference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简短回答:不要使用 r5rs;只需使用母语即可。在 DrRacket 的当前版本中,该语言称为“racket”。这是一个使用框的程序:
FWIW:Greg 的答案比我的更纯粹,但认为 DrRacket(nee DrScheme)中不可用可变结构是错误的。
最后,您滥用了术语“通过引用调用”。盒子只是可变结构,按值调用语言(例如racket、r5rs、java等)可以很好地改变这些结构。
Short answer: don't use r5rs; just use the native language. In current versions of DrRacket, that language is called "racket". Here's a program that uses boxes:
FWIW: Greg's answer is more purely functional than mine, but it would be a mistake to believe that mutable structures are not available in DrRacket (nee DrScheme).
Finally finally, you're misusing the term "call by reference". Boxes are just mutable structures, and a call-by-value language (such as racket, r5rs, java, etc.) can mutate these structures just fine.
Scheme 鼓励您从函数意义上进行思考,而不是通过“通过引用”(这是您在命令式语言中可能执行的操作)。例如,这意味着您的
push
操作将采用两个参数:和返回一个新堆栈,其中包含新元素与其余元素的组合。现有堆栈。类似地,
pop
操作将获取一个堆栈并返回顶部元素消失的堆栈,而peek
将返回顶部元素的值。事实证明,Scheme 中的列表几乎与堆栈一样工作。以下映射将帮助您入门:
Instead of passing "by reference", which is something you might do in an imperative language, Scheme encourages you to think in a functional sense. This means that your
push
operation, for example, would take two parameters:and return a new stack that contains the new element in combination with the rest of the existing stack. Similarly, the
pop
operation would take a stack and return one with the top element gone, andpeek
would return the value of the top element.As it turns out, lists in Scheme work almost exactly like stacks. The following mappings will help you get started: