Thursday 15 April 2010

functional programming - insert-sort with reduce clojure -



functional programming - insert-sort with reduce clojure -

i have function

(defn goneseq [inseq uptil] (loop [counter 0 newseq [] orginseq inseq] (if (== counter uptil) newseq (recur (inc counter) (conj newseq (first orginseq)) (rest orginseq))))) (defn insert [sorted-seq n] (loop [currentseq sorted-seq counter 0] (cond (empty? currentseq) (concat sorted-seq (vector n)) (<= n (first currentseq)) (concat (goneseq sorted-seq counter) (vector n) currentseq) :else (recur (rest currentseq) (inc counter)))))

that takes in sorted-sequence , insert number n @ appropriate position example: (insert [1 3 4] 2) returns [1 2 3 4].

now want utilize function reduce sort given sequence like:

(reduce (insert seq n) givenseq)

what thr right way accomplish this?

if function works inserting single value, work:

(reduce insert [] givenseq)

for example:

user> (reduce insert [] [0 1 2 30.5 0.88 2.2]) (0 0.88 1 2 2.2 30.5)

also, should noted sort , sort-by built in , improve hand-rolled solutions.

clojure functional-programming

No comments:

Post a Comment