Search code examples
clojure

Subtract n from every element of a Clojure sequence


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.


Solution

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