2

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

Aaron Bell
  • 852
  • 2
  • 11
  • 26

2 Answers2

4

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)
cfrick
  • 35,203
  • 6
  • 56
  • 68
Aaron Bell
  • 852
  • 2
  • 11
  • 26
1

You can accomplish something similar with the built-in function juxt:

    (let [all-fns (juxt inc dec)]

      ;=>  (all-fns 42) => [43 41]

One caution: juxt is somewhat obscure and a simpler approach may be better for most problems (and easier for future readers to understand).

Alan Thompson
  • 29,276
  • 6
  • 41
  • 48