0

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))))
    )
4
  • 1
    I'm voting to close this question as off-topic because: It appears to be a simple homework problem. Commented Nov 27, 2018 at 2:41
  • Show the work you have done so far. Commented Nov 27, 2018 at 2:42
  • @AlanThompson That is not the official Stack Overflow policy on homework questions. We care about questions that are well asked, and that is independent of whether they are homework. This one looks fine to me, as it clearly defines the desired behavior and shows an attempt. It's even a working attempt, asking for ways to do it better. Commented Nov 27, 2018 at 19:36
  • The first line was the only thing present when first posted Commented Nov 27, 2018 at 20:52

1 Answer 1

2
(let [A [:q :e :g :t :p]]
    (->> A
         (partition-all 2)
         (mapcat reverse)))
Sign up to request clarification or add additional context in comments.

3 Comments

(map reverse) + flatten == (mapcat reverse)
Indeed. It is more succinct your way.
It's not just more succinct, but more correct. flatten is (almost) never the right answer. Imagine if A were instead defined as [[1 2] [3 4]]. We'd like the result to be [[3 4] [1 2]], but with the flatten version we would get [3 4 1 2].

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.