Skip to content

Instantly share code, notes, and snippets.

@swannodette
Forked from puffnfresh/lens.clj
Created May 30, 2012 02:50
Show Gist options
  • Save swannodette/2833321 to your computer and use it in GitHub Desktop.
Save swannodette/2833321 to your computer and use it in GitHub Desktop.
(def users [{:name "Brian" :age 22} {:name "Ben" :age 19}])
;; Takes a "path", returns a function that takes an "object" and
;; returns a "costate"
(defn lens [p]
(fn [o]
{:get (get-in o p)
:set #(assoc-in o p %1)}))
(def myAgeLens (lens [0 :age]))
(def usersCoState (myAgeLens users))
(println (:get usersCoState))
;; 22
(println ((:set usersCoState) 23))
;; [{:name Brian, :age 23} {:name Ben, :age 19}]
;; Laws
(println (= (:get (myAgeLens ((:set usersCoState) 23))) 23))
(println (= ((:set usersCoState) (:get usersCoState)) users))
(println (= ((:set (myAgeLens ((:set usersCoState) 23))) 24) ((:set usersCoState) 24)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment