Skip to content

Instantly share code, notes, and snippets.

@bmjames
Created September 26, 2012 16:55
Show Gist options
  • Save bmjames/3789162 to your computer and use it in GitHub Desktop.
Save bmjames/3789162 to your computer and use it in GitHub Desktop.
Balanced parentheses using StateT
object PragmaticParens {
import scalaz._, Scalaz._, typelevel._
private def f(c: Char): StateT[Option, Nat, Unit] =
StateT(nat => (c match {
case '(' => Some(nat.succ)
case ')' => nat.pred
case _ => Some(nat)
}) map (_ -> ()))
def balanced(s: String): Boolean =
s.toList.traverse_[({type λ[α]=StateT[Option, Nat, α]})#λ](f).exec(Zero).exists(_.isZero)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment