Skip to content

Instantly share code, notes, and snippets.

@rrees
Created November 7, 2012 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rrees/4034692 to your computer and use it in GitHub Desktop.
Save rrees/4034692 to your computer and use it in GitHub Desktop.
Balanced parens example
(defn balanced?
([s] (apply balanced? 0 (seq s)))
([current-count x & xs]
(let [new-count
(cond
(= x \() (inc current-count)
(= x \)) (dec current-count)
:else current-count)]
(if (< current-count 0) false
(if xs
(apply balanced? new-count xs)
(= 0 new-count))))))
(balanced? " Hello (world))")
(balanced? "Hello )) world ((")
(balanced? "(")
(balanced? "(hello world")
(balanced? "(hello world)")
(apply balanced? 0 (seq "()())("))
(balanced? "())(")
(balanced? "()")
(balanced? "(())")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment