title: Clojure - sort function
body: <p>I am trying to write a recursive sort function that sorts a list from low to high (duh). I am currently getting output, just not the correct output. Here is my code:</p>
  
  <pre><code>(defn sort/predicate [pred loi]
     (if (empty? loi)
       ()
       (if (= (count loi) 1)
         (cons (first loi) (sort pred (rest loi)))
         (if (pred (first loi) (first (rest loi)))
           (cons (first loi) (sort pred (rest loi)))
           (if (pred (first (rest loi)) (first loi))
             (cons (first (rest loi)) (sort pred (cons (first loi) (rest (rest loi)))))
             (cons (first loi) (sort pred (rest loi))))))))
  </code></pre>
  
  <p>Basically, I compare the first two elements in the list and, if the first element is smaller I cons it with the result of comparing the next two elements of the list. If the second element of the list is smaller, I cons the second element with the result of sorting the first two elements of the cons of the first element and everything after the second element (sorry if that's hard to follow). Then, when there is only one element left in the list, I throw it on the end and return it. However, there is a bug along the way somewhere because I should get the following:</p>
  
  <pre><code>&gt;(sort/predicate &lt; '(8 2 5 2 3))
  (2 2 3 5 8)
  </code></pre>
  
  <p>but instead, I get:</p>
  
  <pre><code>&gt;(sort/predicate &lt; '(8 2 5 2 3))
  (2 5 2 3 8)
  </code></pre>
  
  <p>I'm pretty new to clojure, so any help is greatly appreciated. Also, I would like to keep my code roughly the same (I don't want to use a sorting function that already exists). Thanks</p>