I have just start reading Let over lambda and I thought I would try and write a clojure version of the block-scanner in the closures chapter.
I have the following so far:
(defn block-scanner [trigger-string]
(let [curr (ref trigger-string) trig trigger-string]
(fn [data]
(doseq [c data]
(if (not (empty? @curr))
(dosync(ref-set curr
(if (= (first @curr) c)
(rest @curr)
trig)))))
(empty? @curr))))
(def sc (block-scanner "jihad"))
This works I think, but I would like know what I did right and what I could do better.
I would not use
ref-setbutalterbecause you don’t reset the state to a completely new value, but update it to a new value which is obtained from the old one.Then it is not necessary to use refs since you don’t have to coordinate changes. Here an atom is a better fit, since it can be changed without all the STM ceremony.
Next I would get rid of the imperative style.