为什么我可以更改Clojure中的不变变量?
我来自JavaScript世界,该世界用于声明不变变量。
不可变动变量的定义在Clojure中以相同的方式进行解释。
但是,这是允许的:
(def cheese "I like cheese")
...
...
(def cheese "Actually, I changed my mind)
当我运行此功能时,repl给我实际上,我改变了主意
。
在JS中,它将丢弃错误,因为A const
无法更改。
如果有人解释了我对不变变量的理解
在Clojure世界中不正确的情况下,我会很感激?
谢谢
I come from the Javascript world where const is used to declare immutable variables.
The definition of a immutable variable is explained in the same way in Clojure.
However, this is allowed:
(def cheese "I like cheese")
...
...
(def cheese "Actually, I changed my mind)
When I run this, the repl gives me actually, I changed my mind
.
In JS, it will throw an error because a const
cannot be changed.
I would appreciate it if someone explained where my understanding of immutable variables
is incorrect in the clojure world?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确切地说,Clojure具有 不变的值 ,而不是 不可变的变量 。毕竟,名称
var
是“变量”的速记。想象一下数字
5
。您无需担心谁拥有它,或者有人可能会更改其定义。此外,在程序的许多部分中,可能有许多用于许多目的的数字的副本。 Clojure将此想法扩展到诸如vector[1 2 3]
或MAP{:FIRST“ JOE”:最后的“ Cool”}
之类的收集值。话虽如此,在clojure a
var
通常用于从未更改的全局“常数”值(尽管可以)。使用ClojureAtom
(全局或本地)对于确实更改的值是正常的。还有许多其他选项(例如,诸如
的功能,例如具有内部累加器)。此文档源列表变得clojure”和“ Brave Clojure”。
To be precise, Clojure has immutable values, not immutable variables. After all, the name
Var
is shorthand for "variable".Imagine the number
5
. You never need to worry about who "owns" it, or that someone might change its definition. Also, there can be many copies of that number used for many purposes in many parts of your program. Clojure extends this idea to collection values such as the vector[1 2 3]
or the map{:first "Joe" :last "Cool"}
.Having said that, in Clojure a
Var
is normally used for a global "constant" value that is never changed (although it could). Using a ClojureAtom
(global or local) is normal for values that do change. There are many other options (functions likereduce
have an internal accumulator, for example).This list of documentation sources is a good place to start, esp the books "Getting Clojure" and "Brave Clojure".
正如艾伦(Alan)提到的那样,克洛杰尔(Clojure)具有不可变的值,而不是不变的变量。
当您执行
发生的事情时,创建了一个clojure
var
,var绑定到名称(aka符号)x
,而不可变值值42 放置在VAR内。 var是值的容器。通常,只有一个值放在var中。但是,如您的示例中,在不同时间内可以放置不同的不变值。
阅读 clojure vars和全局环境可能会有所帮助。
As Alan mentions, Clojure has immutable values, not immutable variables.
When you execute
what happens is that a Clojure
Var
is created, the Var is bound to the name (aka symbol)x
, and the immutable value42
is placed inside the Var. A Var is a container of values. Typically, only one value is ever placed in a Var. But, as in your example, there can be different immutable values placed inside the Var at different times.Reading Clojure Vars and the Global Environment might be helpful.