Skip to content

Instantly share code, notes, and snippets.

@amalloy
Forked from brehaut/fix-parens.clj
Created March 10, 2011 21:50
Show Gist options
  • Save amalloy/865004 to your computer and use it in GitHub Desktop.
Save amalloy/865004 to your computer and use it in GitHub Desktop.
(use 'name.choi.joshua.fnparse)
(def tokenize (partial re-seq #"[\[\](){}]|[^\[\](){}]+"))
(defn initial-state
[input] {:remainder (tokenize input)
:brackets (list)})
(def brackets {"[" "]" "(" ")" "{" "}"})
(def opening (complex [open (term (set (keys brackets)))
_ (update-info :brackets (partial cons open))]
open))
(def closing (failpoint (term (set (vals brackets)))
(fn [remainder state]
(let [bs (:brackets state)]
(if (or (seq remainder) (empty? bs))
nil
[(first bs) (assoc state :brackets (rest bs))])))))
(def content (term (complement (set (flatten (seq brackets))))))
(def expression (alt (complex [open opening
body (rep* expression)
_ closing]
(str open (apply str body) (brackets open)))
content))
(def fix-parens (comp (partial rule-match expression prn prn)
initial-state))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment