Clojure closure

前端 未结 4 453
迷失自我
迷失自我 2021-01-31 19:43

the other day I was trying to come up with an example of closure in Clojure. I came up with and example I had seen before and thought it was appropriate.

Alas, I was tol

4条回答
  •  不知归路
    2021-01-31 20:37

    Another example of closure. There are two functions that share the same environment (state).

    (defn create-object [init-state]
      (let [state (atom init-state)]
        {:getter (fn []
                   @state)
         :setter (fn [new-val]
                   (reset! state new-val))}))
    
    (defn test-it []
      (let [{:keys [setter getter]} (create-object :init-value)]
        (println (getter))
        (setter :new-value)
        (println (getter))))
    
    (test-it)
    => :init-value
       :new-value
    

提交回复
热议问题