Say I have 2 functions add1 & sub1, as defined below. From these functions I create a vector funclist.
(defn add1
[x]
(+ x 1))
(defn sub1
[x]
(- x 1))
(def funclist (vec '(add1 sub1)))
Suppose now on this list of functions, I want to run a map as below
(map #(% 3) funclist)
This gives me
=> (nil nil)
I was expecting (4 2)...
. What am I doing wrong?
I am a complete Clojure noob... just FYI
-Abe
You turned your functions into symbols w/ the '
.
(map #(type %) funclist) ;; => (clojure.lang.Symbol clojure.lang.Symbol)
Yet, symbols are functions too. They can be used to look-up like get
.
Hence the nil
results:
('inc 42)
; → nil
Change
(def funclist (vec '(add1 sub1)))
to
(def funclist (vector add1 sub1)) ;; or [add1 sub1]
And it will work.
(map #(% 3) funclist) ;;=> (4 2)