Skip to content

Instantly share code, notes, and snippets.

@eneroth
Created September 16, 2018 11:40
Show Gist options
  • Save eneroth/aa712a6c33d8d34cd5423f2d0226beb0 to your computer and use it in GitHub Desktop.
Save eneroth/aa712a6c33d8d34cd5423f2d0226beb0 to your computer and use it in GitHub Desktop.
Uses reduce to check if brackets are balanced
(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