feedback on file parsing with Clojure

98 views
Skip to first unread message

AndyK

unread,
Jun 16, 2017, 12:16:34 PM6/16/17
to Clojure
hello,

i'm looking for some feedback on how i've used Clojure to do some file parsing
still getting the hang of Clojure ways of thinking and i'd love to hear any advice on how to improve what i've done
for example, i'm guessing the way i've used cond blocks is a bit sketchy - at that point, i was kind of in a just-get-it-done mindset 

the file being parsed is here

the code doing the parsing is here

the output is here (a browser JSON viewer is advised)

thank you for any help
a

Justin Smith

unread,
Jun 16, 2017, 1:31:09 PM6/16/17
to Clojure
The primary suggestion I'd make here is to replace the doseq/reset! construction in your main loop with reduce using a hash-map accumulator representing each value you are updating with a separate key. This isn't just more idiomatic, it also performs better.

Instead of:

(let [hexagrams (atom (sorted-map))
      state (atom :do-nothing)
      current-hexagram (atom {})]
  (doseq [line (line-seq rdr)]
    (let [state-machine (@state PRETTY-STATE-MACHINE)
          line-match (re-matches (:regex state-machine) line)
          [new-state new-hexagram] ((:handler state-machine) line-match @current-hexagram)]
      (reset! state new-state)
      (reset! current-hexagram new-hexagram)
      (swap! hexagrams assoc (:king-wen-number new-hexagram) new-hexagram))))

something like:

(reduce (fn [acc line]
          (let [{:keys [state hexagrams current-hexagram]} acc
                state-machine (state PRETTY-STATE-MACHINE)
                line-match (re-matches (:regex state-machine) line)
                [new-state new-hexagram] ((:handler state-machine) line-match current-hexagram)]
            {:state new-state
             :current-hexagram new-hexagram
             :hexagrams (assoc (:king-wen-number new-hexagram) new-hexagram)}))
        (line-seq rdr))

as a more minor issue, we idiomatically use [a b] instead of (vector a b)

--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@googlegroups.com
Note that posts from new members are moderated - please be patient with your first post.
To unsubscribe from this group, send email to
clojure+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups "Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email to clojure+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages