Search code examples
haskellclojurepattern-matchingdestructuring

Destructure a list two elements at a time (Clojure)


This problem takes many forms. For example, given the input '(1 2 3 4 5 6), we might want to swap the values between even and odd pairs. The output would be '(2 1 4 3 6 5).

In Haskell, this is rather easy:

helper [] = []
helper [x] = [x]
helper (x : y : ys) = y : x : helper ys

I wrote some Clojure code to accomplish the same task, but I feel that there is probably a cleaner way. Any suggestions on how to improve this?

(defn helper [[x y & ys]]
  (cond
   (nil? x) (list)
   (nil? y) (list x)
   :else (lazy-seq (cons y (cons x (helper ys))))))

Ideally the list would be consumed and produced lazily. Thanks.


Solution

  • (for [[a b] (partition 2 '(1 2 3 4 5 6))
          i [b a]]
      i)
    

    OR something resembling the haskell version:

    (defn helper
      ([] (list))
      ([x] (list x))
      ([x y & r] (concat [y x] (apply helper r))))
    
    (apply helper '(1 2 3 4 5 6))