Skip to content

Instantly share code, notes, and snippets.

@pilosus
Created October 3, 2021 13:20
Show Gist options
  • Select an option

  • Save pilosus/864265e010e0296accef349e9bd6f427 to your computer and use it in GitHub Desktop.

Select an option

Save pilosus/864265e010e0296accef349e9bd6f427 to your computer and use it in GitHub Desktop.
Check if a string contains balanced parenthesis in Clojure
(def openning ["(" "[" "{"])
(def closing [")" "]" "}"])
(def parens (zipmap openning closing))
(defn parens-balanced?
[s]
(loop [input-string s
stack []]
(if (empty? input-string)
(empty? stack)
(let [character (str (first input-string))
rest-str (apply str (rest input-string))]
(cond
(some #(= character %) openning)
(recur rest-str (conj stack (get parens character)))
(some #(= character %) closing)
(if (or (empty? stack) (not= (last stack) character))
false
(recur rest-str (pop stack)))
:else (recur rest-str stack))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment