如何在PLT方案中定义常量?
如何声明符号始终代表特定值并且在程序执行过程中不能更改?
How do I declare that a symbol will always stand for a particular value and cannot be changed throughout the execution of the program?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
据我所知,这在Scheme中是不可能的。 而且,无论出于何种意图和目的,这并不是绝对必要的。 只需像常规变量一样在顶层定义值,然后不要更改它。 为了帮助您记住,您可以采用命名这些常量的约定 - 我见过一些书籍,其中顶级变量的名称周围使用
*stars*
进行定义。在其他语言中,存在某些库会覆盖您创建的定义的危险。 然而,Scheme 的词法作用域与 PLT 的模块系统相结合,确保这种情况永远不会发生。
As far as I know, this isn't possible in Scheme. And, for all intents and purposes, it's not strictly necessary. Just define the value at the toplevel like a regular variable and then don't change it. To help you remember, you can adopt a convention for naming these kinds of constants - I've seen books where toplevel variables are defined with
*stars*
around their name.In other languages, there is a danger that some library will override the definition you've created. However, Scheme's lexical scoping coupled with PLT's module system ensure this will never happen.
在 PLT 方案中,您在自己的模块中编写定义 - 如果您自己的代码没有使用“set!”,则绑定永远不会改变。 事实上,编译器使用它来执行各种优化,因此这不仅仅是一个约定。
In PLT Scheme, you write your definitions in your own module -- and if your own code is not using `set!', then the binding can never change. In fact, the compiler uses this to perform various optimizations, so this is not just a convention.
您可以定义一个计算结果为常量的宏,这将保护您免受
set!
的简单使用,然后您只需在任何地方使用
(constant)
即可,这与打字无关*持续的 *You could define a macro that evaluates to the constant, which would protect you against simple uses of
set!
Then you just use
(constant)
everywhere, which is no more typing than *constant *我想到的一个非常黑客的答案是定义一个返回常量的读取器宏:
然后就不可能重新定义它(不更改您的读取器宏):
A really hackish answer that I thought of was to define a reader macro that returns your constant:
It would then be impossible to redefine this (without changing your reader macro):