Map with clojure re-argument

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 the card:

(map f [1 2 6 3 6] [2 2 2 2 2])

But it seems a little ugly to create a second vector where each element is exactly the same.

So I thought using 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 a map when some arguments don't change?

+4
source share
2 answers

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 to

(map f [1 2 6 3 6] (repeat 2))

Approach 2 : using an anonymous function

(map #(f % 2) [1 2 6 3 6])
+2

partial

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

Source: https://habr.com/ru/post/1535057/


All Articles