Last active
December 15, 2015 07:39
-
-
Save devth/5225437 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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"))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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