4
votes

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?

2
Use mapv instead of map, and you'll get another vector. map's laziness doesn't buy you anything here.Thumbnail

2 Answers

4
votes

Just apply partial function

(map (partial + 2) [1 2 6 3 6]) => (3 4 8 5 8)
2
votes

Approach 1: use repeat.

(repeat 2) gives you a lazy sequence of infinite 2s

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])