Skip to content

Instantly share code, notes, and snippets.

@timsgardner
Last active December 13, 2015 17:26
Show Gist options
  • Save timsgardner/290125b7be533f57b63c to your computer and use it in GitHub Desktop.
Save timsgardner/290125b7be533f57b63c to your computer and use it in GitHub Desktop.
parse
(defn parse-form [down-tok?, up-tok?, [tok & toks]]
(loop [frm [tok], toks toks]
(if-let [[tok2 & toks2] (seq toks)]
(cond
(down-tok? tok2) (let [[res toks3] (parse-form down-tok?, up-tok?, toks)]
(recur (conj frm res) toks3))
(up-tok? tok2) [(conj frm tok2) toks2]
:else (recur (conj frm tok2) toks2))
[frm nil])))
(defn parse [down-tok?, up-tok?, toks]
(loop [top [], toks toks]
(if-let [[tok & rtoks] (seq toks)]
(if (down-tok? tok)
(let [[res toks2] (parse-form down-tok? up-tok? toks)]
(recur (conj top res) toks2))
(recur (conj top tok) rtoks))
top)))
@timsgardner
Copy link
Author

For when copying 18 lines is better than including a real parsing library

(parse
  #{:down}
  #{:up}
  [:a :down :b :down :c :up :up :down :d :up])

=> [:a [:down :b [:down :c :up] :up] [:down :d :up]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment