Skip to content

Instantly share code, notes, and snippets.

@benknoble
Last active February 13, 2020 03:18
Show Gist options
  • Save benknoble/f6d157217a7a814450d6fc9cf45625ee to your computer and use it in GitHub Desktop.
Save benknoble/f6d157217a7a814450d6fc9cf45625ee to your computer and use it in GitHub Desktop.
Balanced parentheses checker in a balanced parentheses language
(ns parens)
(defn mk-balanced?
"makes a balanced? checker from table, which maps closing characters to
opening characters.
see also: balanced?"
[table]
(fn [s]
(let [opens (set (vals table))
closes (set (keys table))]
(->> s
seq
(reduce
(fn [stack cur]
(condp contains? cur
opens (conj stack cur)
closes (if (and (seq stack)
(= (peek stack) (table cur)))
(pop stack)
(reduced [:false]))
stack))
[])
empty?))))
(def balanced?
(mk-balanced? {\) \(
\] \[
\} \{}))
(comment
(->> "parens.clj"
slurp
balanced?) ;=> false
(->> "parens.clj"
slurp
reverse
(drop 304) ;; length of balanced? form + this comment
reverse
balanced?) ;=> true
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment