为什么我的地图没有更新?

时间:2016-04-20 20:12:56

标签: clojure

对clojure来说很新,所以要善良。

(def state {:currentPosition "1"})

(while (not= (state :currentPosition) "2") ; this is true
  (assoc state :currentPosition "2") ; 
)    

这导致无限循环,它不会运行,但我不明白为什么。条件

 (not= (state :currentPosition) "2")

是真的

因此,循环开始,然后在循环内,我正在更新状态。为什么没有循环结束而只是停止灯表?感谢

1 个答案:

答案 0 :(得分:6)

Clojure datastructures是不可变的,因此(assoc state :currentPosition "2")不会改变分配给state var的对象,只会返回新版本的地图。

如果要修改变量中的值,则需要将它们包含在Clojure's refs之一中。例如,您可以使用atom

(def state (atom {:currentPosition 1}))

(reset! state {:currentPosition 2})    
@state ;; => {:currentPosition 2}

(swap! state update :currentPosition inc)
@state ;; => {:currentPosition 3}
相关问题