8
 (def tmp = [ 1 2 3 9 4 8])

I'm trying to create pairs of 2, then for each pair, subtract the second number from the first. desired result: (1 6 4)

Here is what I was trying:

(map #(apply - %2 %1) (partition 2 tmp))

how can I do this?

1
  • From the example it looks like you subtract the first number from the second, not the other way around, right? Commented Oct 9, 2012 at 20:30

3 Answers 3

11

Partition produces a sequence of sequences so the function you map over them needs to expect a sequence of two items. There are several ways to express this:

(def tmp  [ 1 2 3 9 4 8])

user> (map #(- (second %) (first %)) (partition-all 2 tmp ))
(1 6 4)

user> (map #(apply - (reverse %)) (partition-all 2 tmp ))
(1 6 4)

user> (map (fn [[small large]] (- large small)) (partition-all 2 tmp ))
(1 6 4)

The version using apply is different because it will still "work" on odd length lists:

user> (map #(apply - (reverse %)) (partition-all 2 [1 2 3 4 5 6 7] ))
(1 1 1 -7)

The others will crash on invalid input, which you may prefer.

Sign up to request clarification or add additional context in comments.

Comments

2

Here's a solution using reduce

(reduce #(conj %1 (apply - (reverse %2)))  [] (partition-all 2 [1 2 3 9 4 8])) 
=> [1 6 4]

1 Comment

(reduce (conj ...)) ia a cool way to express a non-lazy version of map. Check out the new reducers library for a bunch more on this topic: clojure.com/blog/2012/05/08/… if you are interested
0

I wonder why this solution was overlooked...

Since switching the order of subtraction is simply the negative of the original subtraction, (a-b=-(b-a)), the solution becomes more efficient (only in this particular case!!)

(map #(- (apply - %)) (partition-all 2 [1 2 3 9 4 8]))

Pedagogically, Arthur's solution is correct. This is just a solution that is more suited the specfic question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.