Block-Scanner from Let Over Lambda in Clojure

Remember Getting my head around let-over-lambda, functions in let, and let with bindings in Clojure in which I mentioned the chapter Closures in Let Over Lambda by Doug Hoyte? I spent an entire day having imagined I could write the parser in Clojure and, guess what, I ultimately did it!

How would you feel about the following implementation? Would you accept it as a preliminary version of a final solution or would that be the final one?

user=> (defn block-scanner [trigger-string]
         (let [curr (atom trigger-string)]
           (fn 
             ([] @curr)
             ([data-string]
               (doseq [c data-string]
                 (if @curr
                   (swap! curr (fn [_]
                                 (if (= (first @curr) c)
                                   (rest @curr)
                                   trigger-string)))))
               (= @curr trigger-string)))))
#'user/block-scanner
user=> (def clj-scan (block-scanner "clojure"))
#'user/clj-scan
user=> (clj-scan ">> cloj")
false
user=> (clj-scan)
(\u \r \e)
user=> (clj-scan "ure.")
true

Notice how the returned function (a closure) closes over the atom (in the let form) and trigger-string (the input argument). I hope my Clojure self-learning is going into the right direction.

Be Sociable, Share!
This entry was posted in Languages.

3 Responses to Block-Scanner from Let Over Lambda in Clojure

  1. Konrad Garus says:

    It does not execute:

    doseq requires a vector for its binding

    Unable to resolve symbol: c in this context

Leave a Reply

%d bloggers like this: