Skip to main content
1 of 3
Thumbnail
  • 1.6k
  • 9
  • 16

I'd never thought of using reduce for this. Neat! However, you can simplify mk-balanced? a little.

  • str->chars is redundant. Clojure's sequence functions accept strings as such.
  • You can use reduced to short circuit a reduce.
  • The reduced can return any non-empty sequence: no need for [:false].

The simplified version is ...

(defn mk-balanced? [table]
  (fn [s]
    (let [opens (set (vals table))
          closes (set (keys table))]
      (empty?
        (reduce
          (fn [stack cur]
            (condp
              contains? cur
              opens (conj stack cur)
              closes (if (and (seq stack)
                              (= (peek stack) (table cur)))
                       (pop stack)
                       (reduced [nil]))
              stack))
          []
          s)))))
Thumbnail
  • 1.6k
  • 9
  • 16