Skip to content

Instantly share code, notes, and snippets.

@devth
Last active December 15, 2015 07:39
Show Gist options
  • Save devth/5225437 to your computer and use it in GitHub Desktop.
Save devth/5225437 to your computer and use it in GitHub Desktop.
(ns user)
(def matches?
(let [match-map {\{ \}
\[ \]
\( \)}
open-set (set (keys match-map))
close-set (set (vals match-map))]
(fn [input]
(try
(empty?
(reduce
(fn [acc c]
(cond
(open-set c) (conj acc c)
(close-set c) (let [[x & rest] acc]
(if (= (match-map x) c)
rest
(throw (Exception.))))
:else acc))
(list)
input))
(catch Exception e false)))))
(assert (matches? "{foo}"))
(assert (not (matches? "foo}")))
(assert (not (matches? "{foo")))
import scala.util.Try
object Matches {
val MatchMap = Map('{' -> '}', '[' -> ']', '(' -> ')')
def doesMatch(input: String): Boolean =
Try(input.foldLeft(List[Char]()) { (acc, c) =>
if (MatchMap.keySet.contains(c))
c :: acc
else if (MatchMap.values.toSet.contains(c))
acc match {
case x :: rest if MatchMap(x) == c => rest
}
else
acc
}.isEmpty).getOrElse(false)
assert(doesMatch("{{foo} [bar] (baz)}"))
assert(!doesMatch("{foo(})"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment