Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Here's the code...

My goal is to simulate a Pile shuffle of a vector.

Here's the function..

(defn pile
  ([cards] (pile cards 3 1))
  ([cards num_piles] (pile cards num_piles 1))
  ([cards num_piles times]
    (loop [i 1
           piles (transient (vec (map (fn [p] []) (range num_piles))))
           the_pile 0]
      (if (<= i (count cards))
        (recur (inc i)
                 (vec (concat [(nth cards (dec i))]
                               (nth piles the_pile))))
               (rem i num_piles))
        (if (> times 1)
          (pile (reduce into (persistent! piles)) num_piles (dec times) )
          (vec (reduce into (persistent! piles))))))))

It takes 2 optional arguments for the number of piles to use and how many times to perform the shuffle.

As this is my first attempt at clojure code, I'm fairly sure I'm doing something terribly wrong here... I'm also concerned with speed and efficiency.

Also I'd appreciate any pointers that would make this function more generic (maybe not restricting to vectors, but general collections)

Also, indentation style.

share|improve this question
add comment

1 Answer 1

You need loop/recur very rarely in most code, and almost never for operating on collections/sequences. Using the standard library sequence functions, it’s possible to do the main pile shuffle with just a handful of expressions:

(->> (range (dec n) -1 -1) (mapcat #(take-nth n (drop % cards))) reverse)

It takes some getting used to, and familiarity with the Clojure standard library. When I was first getting started, I found it immensely helpful to read the clojure/core.clj code. It isn’t all idiomatic because it’s building the support for the idioms as it goes, but it demonstrates what Clojure makes possible and how it makes those things possible.

share|improve this answer
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.