Skip to content

Instantly share code, notes, and snippets.

@jjttjj
Created June 16, 2020 13:22
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 jjttjj/6cef4c2c8e1ed7e5907ced6074199ae3 to your computer and use it in GitHub Desktop.
Save jjttjj/6cef4c2c8e1ed7e5907ced6074199ae3 to your computer and use it in GitHub Desktop.
(def st {:things [{:x 1} {:x 2} {:x 3}]
:location 0})
(defn advance [st]
(assert (< (:location st) (dec (count (:things st)))))
(let [old-loc (:location st)
new-loc (inc old-loc)]
(assoc st
:location new-loc
:last-changes {:last-item (nth (:things st) old-loc)
:current-item (nth (:things st) new-loc)}
)))
(pprint (advance st))
;;=>
{:things [{:x 1} {:x 2} {:x 3}],
:location 1,
:last-changes {:last-item {:x 1}, :current-item {:x 2}}}
(defn split-thing [st ix]
(assert (< ix (count (:things st))))
(let [upto (take ix (:things st))
loc (last upto)
[after :as rst] (drop ix (:things st))
new-x (/ (+ (:x loc) (:x after)) 2)
new-thing {:x new-x}]
(assoc st
:things (concat upto [new-thing] rst)
:last-changes {:inserted {1 new-thing}})))
(pprint (split-thing st 1))
;;=>
{:things ({:x 1} {:x 3/2} {:x 2} {:x 3}),
:location 0,
:last-changes {:inserted {1 {:x 3/2}}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment