Skip to content

Instantly share code, notes, and snippets.

@mamboking
Created August 16, 2011 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mamboking/1150106 to your computer and use it in GitHub Desktop.
Save mamboking/1150106 to your computer and use it in GitHub Desktop.
Cyclic sorted list
;;cyclic list insertion
(def start-node (atom [1 (fn [] start-node)]))
(defn insert-after [node val]
(let [new-node (atom [val (last @node)])]
(swap! node (fn [n] [(first n) (fn [] new-node)]))))
(defn find-insert-spot [node val]
(loop [cnode node
ctr 0]
(let [next-node ((last @cnode))
cval (first @cnode)
nval (first @next-node)]
(if (= next-node node)
cnode
(if (or (<= cval val nval)
(and (> cval nval) (or (>= val cval)
(<= val nval))))
cnode
(recur next-node (inc ctr)))))))
(defn insert-val [node val]
(insert-after (find-insert-spot node val) val))
(defn get-nth-after [start cnt]
(loop [cnode start i cnt]
(if (= i 0)
cnode
(recur ((last @cnode)) (dec i)))))
(defn ring-vals [start]
(loop [cnode start
acc []]
(let [next-node ((last @cnode))
cval (first @cnode)]
(if (= next-node start)
(conj acc cval)
(recur next-node (conj acc cval))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment