Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure map over sequence of pairs

Tags:

clojure

 (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?

like image 351
Rob Buhler Avatar asked Oct 09 '12 18:10

Rob Buhler


2 Answers

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.

like image 149
Arthur Ulfeldt Avatar answered Oct 16 '22 16:10

Arthur Ulfeldt


Here's a solution using reduce

(reduce #(conj %1 (apply - (reverse %2)))  [] (partition-all 2 [1 2 3 9 4 8])) 
=> [1 6 4]
like image 26
noahlz Avatar answered Oct 16 '22 17:10

noahlz