方案R5RS:按引用传递

发布于 2024-10-06 09:18:41 字数 122 浏览 7 评论 0原文

我正在尝试模拟方案中的堆栈。我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤凫 2024-10-13 09:18:41

简短回答:不要使用 r5rs;只需使用母语即可。在 DrRacket 的当前版本中,该语言称为“racket”。这是一个使用框的程序:

#lang racket 

(define b (box 234))

(set-box! b 333)

(unbox b)

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:

#lang racket 

(define b (box 234))

(set-box! b 333)

(unbox b)

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.

平安喜乐 2024-10-13 09:18:41

Scheme 鼓励您从函数意义上进行思考,而不是通过“通过引用”(这是您在命令式语言中可能执行的操作)。例如,这意味着您的 push 操作将采用两个参数:

  • 一个堆栈
  • 、一个新元素

返回一个新堆栈,其中包含新元素与其余元素的组合。现有堆栈。类似地,pop 操作将获取一个堆栈并返回顶部元素消失的堆栈,而 peek 将返回顶部元素的值。

事实证明,Scheme 中的列表几乎与堆栈一样工作。以下映射将帮助您入门:

  • push - cons
  • pop -rest
  • peek -first

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:

  • a stack
  • a new element

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, and peek 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:

  • push - cons
  • pop - rest
  • peek - first
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文