(def matches {\( \) \[ \]})

(defn balanced? [s]
  (empty? (reduce #(if (= (matches (peek %1)) %2) (pop %1) (conj %1 %2)) []
s)))

Learning Clojure. So far I'm really liking it. This is the first time I've
tried anything outside of some REPL incantations from books, blogs, this
list, etc thus it wouldn't be a total surprise if it's not idiomatic or
correct in some way. It does seem to work although it could be more
efficient if it could bail earlier on some of the false strings

On Fri, Jul 3, 2009 at 9:13 PM, carlitos <carlos.un...@gmail.com> wrote:

>
>
> Probably the following is much less efficient than the other solutions
> proposed, but I find it easier to understand (and if I didn't
> misunderstand the problem it gives the right answer).
>
> (defn simplify-1
>  "remove adjacent pairs of opening/closing brackets"
>  ([string] (simplify-1 "" string))
>  ([prefix [a & [b & cdef :as bcdef]]]
>     (cond (nil? a) prefix
>           (#{"()" "[]"} (str a b)) (recur prefix cdef)
>           :otherwise (recur (str prefix a) bcdef))))
>
> (defn simplify [s]
>  (let [ss (simplify-1 s)]
>    (if (= ss s) ss (recur ss))))
>
> (defn balanced? [s]
>  (empty? (simplify s)))
>
> Cheers,
>
> Carlos
> >
>

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to