在clojure中的不变性是否与按值传递不同?

pet*_*erc 3 functional-programming clojure

我刚刚开始使用Clojure而且我没有fp经验,但我注意到的第一件事就是强调不变性.然而,我对重点感到有些困惑.看起来您可以轻松地重新定义全局变量,从根本上为您提供一种改变状态的方法.我能看到的最重要的区别是函数参数是按值传递的,不能在函数内重新定义.这是一个显示我的意思的repl片段:

 towers.core=> (def a "The initial string")
 #'towers.core/a
 towers.core=> a
 "The initial string"
 towers.core=> (defn mod_a [aStr]
     #_=>   (prn aStr)
     #_=>   (prn a)
     #_=>   (def aStr "A different string")
     #_=>   (def a "A More Different string")
     #_=>   (prn aStr)
     #_=>   (prn a))
 #'towers.core/mod_a
 towers.core=> a
 "The initial string"
 towers.core=> (mod_a a)
 "The initial string"
 "The initial string"
 "The initial string"
 "A More Different string"
 nil
 towers.core=> a
 "A More Different string"
Run Code Online (Sandbox Code Playgroud)

如果我通过将它视为价值传递而开始理解clojure中的不变性,那么我错过了什么?

Mar*_*cin 9

按值调用和不变性是两个完全不同的概念.实际上,变量不变性的一个优点是这些变量可以通过名称或引用传递,而不会对程序行为产生任何影响.

简而言之:不要将它们视为联系.