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"))
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"))
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.
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"]]
#()
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])