Skip to content

Instantly share code, notes, and snippets.

@tolitius
Last active September 29, 2015 23:28
Show Gist options
  • Save tolitius/1686209 to your computer and use it in GitHub Desktop.
Save tolitius/1686209 to your computer and use it in GitHub Desktop.
checks if a given code snippet parentheses are balanced
(ns balance-check.core)
(defn balanced? [s]
(-> (reduce (fn [[h & r :as stack] c]
(case c
\( (conj stack 42)
\) (if (= h 42)
r
(conj stack "unbalanced"))
stack))
'() s)
empty?))
(ns balance-check.test.core
(:use [balance-check.core]
[clojure.test]))
(deftest check-balanced
(is (balanced? "()"))
(is (balanced? "(a)"))
(is (balanced? "((a))"))
(is (balanced? "((a)(b))"))
(is (balanced? "(((a)(b)c))"))
(is (balanced? "(a (b (c d k (m)) v))")))
(deftest check-unbalanced
(is (not (balanced? ")(")))
(is (not (balanced? "()(")))
(is (not (balanced? ")())")))
(is (not (balanced? "(()(")))
(is (not (balanced? "(a (b (c d k (m) v))")))
(is (not (balanced? ")(a (b (c d k (m) v))")))
(is (not (balanced? "(a (b (c d( k (m) v)((()")))
(is (not (balanced? "(a (b (c d( k (m) v)(((")))
(is (not (balanced? "(a (b) (c d k (m) )))v))"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment