Field accessors as functions in clojure?
Is there a way to convert field feature accessors? I was very surprised when I tried to do this.
(map .x [o1 o2])
but instead had to do this
(defn x [o] (.x o))
(map x [o1 o2])
which seems overkill. Is there a way to create this function for you?
+3
Cristian Garcia
source
to share
2 answers
You can write your own macro to create an anonymous function:
(defmacro field [m] `(fn [x#] (. x# ~m)))
Then, for example,
((field x) (java.awt.Point. 3 5))
;3
+1
Thumbnail
source
to share
Use anonymous fn
(map #(.x %) [o1 o2])
(map (fn [o] (.x o)) [o1 o2])
Or memfn - I was reading anonymous fn
. I will try to find the article.
(map (memfn x) [o1 o2])
Edit : Stu Halloway has this one to say aboutmemfn
+7
Kyle
source
to share