Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericnormand/3340346ecefea234ff6a to your computer and use it in GitHub Desktop.
Save ericnormand/3340346ecefea234ff6a to your computer and use it in GitHub Desktop.
Clojure Lens Implementation
(defn lens [getter setter]
(fn [fmap vf in]
(fmap (partial setter in)
(vf (getter in)))))
(defn lupdate [lens f in]
(lens (fn [f a] (f a))
f
in))
(defn lset [lens in v]
(lupdate lens in (constantly v)))
(defn lget [lens in]
(lens (fn [_ a] a)
identity
in))
(deftype Person [name salary address])
(deftype Address [street zip])
(def lname (lens #(.name %) (fn [p n] (Person. n (.salary p) (.address p)))))
@ericnormand
Copy link
Author

Haskell uses the Functor type to select fmap implementation. Why not pass in fmap directly?

@cgrand
Copy link

cgrand commented Jul 15, 2014

Because you explicitely pass fmap I prefer your impl to @ctford's one.
I think line 12 should be (lupdate lens (constantly v) in))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment