Created
September 16, 2018 11:40
-
-
Save eneroth/aa712a6c33d8d34cd5423f2d0226beb0 to your computer and use it in GitHub Desktop.
Uses reduce to check if brackets are balanced
This file contains 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
(def brackets {\{ \} | |
\[ \] | |
\( \)}) | |
(defn checker [stack char] | |
(if (some #{char} (keys brackets)) ;; Is the character an opening bracket? | |
(conj stack char) | |
(let [closing-char (get brackets (last stack))] | |
(if (= closing-char char) | |
(pop stack) ;; Remove the last character in the stack | |
(reduced (conj stack char)))))) ;; Stop. It's unbalanced. Make sure stack is not empty to induce `false` in parent function. | |
(defn is-balanced [s] | |
(let [all-brackets (set (into (keys brackets) (vals brackets))) | |
chars (filter all-brackets s)] | |
(empty? (reduce checker [] chars)))) | |
(is-balanced "[hello (world)]") | |
;; => true | |
(is-balanced "[hello (world]") | |
;; => false | |
(is-balanced "[hello (world)]))))") | |
;; => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment