Advertisement
kakel

Clojure - Match Parantheses

Jul 23rd, 2012
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ;; The purpose of the function is to match all unmatched parentheses in a given string
  2. ;; ") (()(" ===> "() (()())"
  3.  
  4. ;; The function will loop through a given string one character at a time.
  5. ;; The count of (currently) unmatched left parentheses will be increased by one for each "(" found.
  6. ;; For each ")" found, two things might happen:
  7. ;; If there's currently any unmatched lefties, decrease the count of unmatched left parentheses by 1
  8. ;; (since we've found a matched pair)
  9. ;; Otherwise, if there's no unmatched "(", increase the count of unmatched right parenthesis by 1
  10. ;; (since the found ")" has no preceding partner)
  11. ;; Finally, add the appropriate amount of left and right parenthesis on each side of the string
  12. ;; so that every parenthesis has a matching partner in the returned result
  13.  
  14. (defn match-parantheses [the-string]
  15.   (loop [index 0
  16.          unmatched-left 0
  17.          unmatched-right 0]
  18.     (if (< index (count the-string))
  19.       (let [char (get the-string index)]
  20.         (cond
  21.           (= \( char) (recur (inc index) (inc unmatched-left) unmatched-right)
  22.           (= \) char) (if (= unmatched-left 0)
  23.                         (recur (inc index) unmatched-left (inc unmatched-right))
  24.                         (recur (inc index) (dec unmatched-left) unmatched-right))
  25.           :else (recur (inc index) unmatched-left unmatched-right)))
  26.       (str
  27.         (apply str (repeat unmatched-right "( "))
  28.         the-string
  29.         (apply str (repeat unmatched-left ") "))))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement