Skip to content

Instantly share code, notes, and snippets.

@PEZ
Last active January 12, 2025 22:37
Show Gist options
  • Select an option

  • Save PEZ/6b8d50ee0811042bdc646dc9060037e8 to your computer and use it in GitHub Desktop.

Select an option

Save PEZ/6b8d50ee0811042bdc646dc9060037e8 to your computer and use it in GitHub Desktop.
Balancing Brackets – Rich 4Clojure Problem 177 – See: https://github.com/PEZ/rich4clojure
(ns rich4clojure.medium.problem-177
(:require [hyperfiddle.rcf :refer [tests]]))
;; = Balancing Brackets =
;; By 4Clojure user: daowen
;; Difficulty: Medium
;; Tags: [parsing]
;;
;; When parsing a snippet of code it's often a good idea
;; to do a sanity check to see if all the brackets match
;; up. Write a function that takes in a string and returns
;; truthy if all square [] round () and curly {} brackets
;; are properly paired and legally nested, or returns
;; falsey otherwise.
(def __ :tests-will-fail)
(comment
)
(tests
"This string has no brackets." :=
"class Test {
public static void main(String[] args) {
System.out.println(\"Hello world.\");
}
}" :=
(__ "(start, end]") :=
(__ "())") :=
(__ "[ { ] } ") :=
"([]([(()){()}(()(()))(([[]]({}()))())]((((()()))))))" :=
(__ "([]([(()){()}(()(()))(([[]]({}([)))())]((((()()))))))") :=
(__ "[") :=)
;; To participate, fork:
;; https://github.com/PEZ/rich4clojure
;; Post your solution below, please!
@oezg
Copy link

oezg commented Jan 12, 2025

(defn brackets [[h & t :as stack] br]
  (case br
    (\( \{ \[) (cons br stack)
    (\) \} \]) (case (str h br) ("()" "[]" "{}") t (reduced [h]))
    stack))

(defn balanced? [s]
  (->> s (reduce brackets '()) empty?))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment