Last active
September 29, 2015 23:28
-
-
Save tolitius/1686209 to your computer and use it in GitHub Desktop.
checks if a given code snippet parentheses are balanced
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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?)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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