Subtract n from every element of a Clojure sequence

Viewed 442

I assume this is a very simple question, but I can't seem to find the answer online: how do you subtract n from every element of a Clojure sequence? E.g subtract 4 from each element of (6 9 11) and get (2 5 7)?

I assume this should be done with map, and I know that for the special case of subtracting 1 I can do (map dec (sequence)), but how do I do it for any other case?

For what it's worth, I figured out eventually that (map - (map (partial - n) (sequence)) technically does work, but it's clearly not how this is meant to be done.


For anyone who lands here from search and has a slightly different problem: if you want to subtract every element of a Clojure sequence from n, you can do that with (map (partial - n) (sequence))

Similarly, for multiplying every element of a Clojure sequence by n you can do (map (partial * n) (sequence))

For adding n to every element of a Clojure sequence (map (partial + n) (sequence))

I found that answer in these Clojure docs so I assume it's idiomatic, but obviously I'm not able to vouch for that myself.

3 Answers

An anonymous function literal is convenient here:

> (map #(- % 4) [6 9 11])
(2 5 7)

The #(- % 4) form is short-hand for the anonymous function in

> (map (fn [x] (- x 4)) [6 9 11])
(2 5 7)

If you're looking for a combinatory expression for the function you want, try (comp - (partial - 4)):

=> (map (comp - (partial - 4)) '(6 9 11))
(2 5 7)

Remember that + and - are just ordinary named Clojure functions. The function that you need is probably not worth naming, so you express it directly as #(- % 4) or (fn [n] (- n 4)), or as above.

It is also worth remembering that map is lazy, so can deal with endless sequences:

=> (take 10 (map (comp - (partial - 4)) (range)))
(-4 -3 -2 -1 0 1 2 3 4 5)

This can be achieved through maps. Clojure maps takes a function and list as an argument. Synatax:

(map (function) (seq))

test=> (map (fn[arg] (- arg 4) ) '(7 8 9) )
(3 4 5)
test=> (map (fn[arg] (- arg 4) ) [7 8 9] )
(3 4 5)

Map can take function in shorthand notation too.

(- % 4)

. Here % is argument passed. Defaults to first argument. %1 to explicitly say first argument

test=> (map #(- %1 4) [7 8 9])
(3 4 5)
test=> (map #(- % 4) [7 8 9])
(3 4 5)
Related