1

I was building a function to put strings inside of vectors.

I can't figure out though, why does this work:

(mapv (fn [i] [i]) '("hi" "there"))

but this doesn't work:

(mapv #([%]) '("hi" "there"))

Micah
  • 10,295
  • 13
  • 66
  • 95
  • 1
    Answered [here](http://stackoverflow.com/q/13204993) and [here](http://stackoverflow.com/q/4921566). – glts May 04 '16 at 22:11

3 Answers3

3

See: https://clojuredocs.org/clojure.core/fn#example-560054c2e4b08e404b6c1c80

In short: #(f) == (fn [] (f)), therefore #([1 2 3]) == (fn [] ([1 2 3]))

Hope it helps.

dsm
  • 10,263
  • 1
  • 38
  • 72
2

As glts mentioned, the anonymous function reader macro wraps its body in a list, like this:

(read-string "#([%])")
;=> (fn* [p1__20620#] ([p1__20620#]))

Usually for situations where you need to write an anonymous function whose body is a vector, I'd recommend just using the fn macro as you've done in your question:

(mapv (fn [i] [i]) '("hi" "there"))
;=> [["hi"] ["there"]]

In this case, though, your (fn [i] [i]) is equivalent to the built-in vector function, so I'd suggest you use that instead:

(mapv vector '("hi" "there"))
;=> [["hi"] ["there"]]
Community
  • 1
  • 1
Sam Estep
  • 12,974
  • 2
  • 37
  • 75
1

#() expects a function as its first argument. You could do #(vector %)

e.g:

(map #(vector %) (range 5))
> ([0] [1] [2] [3] [4])

Of course you could also just do:

(map vector (range 5))
> ([0] [1] [2] [3] [4])
Shlomi
  • 4,708
  • 1
  • 23
  • 32