Ceylon Boy
Ceylon Boy

Reputation: 29

Clojure swapping elements in an input sequence

How do you swap adjacent elements in an input sequence using clojure. [10 15 20 25] ---> [15 10 25 20] [:q :e :g :t :p] ---> [:e :q :t :g :p]

this is how i did it, but pretty sure there are better ways to do it!

(defn switch [s]
(loop [[a b & rest] s
       result []]
  (if (empty? rest)
    (cond
        ;;empty sequence
        (empty? s) result
        ;;odd sequence
        (nil? b) (conj result a)
        ;;even sequence
        :else (conj result b a)
    )
    (recur rest (conj result b a))))
    )

Upvotes: 0

Views: 256

Answers (1)

akond
akond

Reputation: 16035

(let [A [:q :e :g :t :p]]
    (->> A
         (partition-all 2)
         (mapcat reverse)))

Upvotes: 2

Related Questions