Reputation: 35692
I'm trying to make traversing nested lists to collect pairs more idiomatic in Clojure
(def mylist '(
(2, 4, 6)
(8, 10, 12)))
(defn pairs [[a b c]]
(list (list a c)(list b c)))
(mapcat pairs mylist)
;((2 6) (4 6) (8 12) (10 12))
Can this be made more elegant?
Upvotes: 2
Views: 226
Reputation: 6073
Just to add more solutions (not elegant or intuitive; do not use ;) ):
(mapcat
(juxt (juxt first last) (juxt second last))
[[2 4 6] [8 10 12]])
;; => ([2 6] [4 6] [8 12] [10 12])
Or this one:
(mapcat
#(for [x (butlast %) y [(last %)]] [x y])
[[2 4 6] [8 10 12]])
;; => ([2 6] [4 6] [8 12] [10 12])
Upvotes: 2
Reputation: 10789
Your code is good, but I would use vectors instead of lists
(defn pairs [[x1 x2 y]]
[[x1 y] [x2 y]])
(mapcat pairs mylist)
Upvotes: 3