Reputation: 656
Consider the following function as an example:
(defn f [x y] (+ x y))
I want to use this function to add 2 to each element of a vector:
[1 2 6 3 6]
I can use map:
(map f [1 2 6 3 6] [2 2 2 2 2])
But it seems a little ugly creating the second vector where every element is exactly the same.
So I thought using a closure was a better approach:
(map (fn g [x] (f x 2)) [1 2 6 3 6])
So my question is:
In clojure, what is the best way to use map when some arguments are not changing?
Upvotes: 4
Views: 419
Reputation: 4010
Approach 1: use repeat.
(repeat 2)
gives you a lazy sequence of infinite 2
s
In your case,
(map f [1 2 6 3 6] [2 2 2 2 2])
should be converted into
(map f [1 2 6 3 6] (repeat 2))
Approach 2: use anonymous function
(map #(f % 2) [1 2 6 3 6])
Upvotes: 2
Reputation: 10789
Just apply partial
function
(map (partial + 2) [1 2 6 3 6]) => (3 4 8 5 8)
Upvotes: 4