Skip to content

Instantly share code, notes, and snippets.

@lauris
Created September 18, 2013 07:31
Show Gist options
  • Save lauris/6605738 to your computer and use it in GitHub Desktop.
Save lauris/6605738 to your computer and use it in GitHub Desktop.
A recursive function which verifies the balancing of parentheses in a string, which we represent as a List[Char]. Recfun 2013, Week 1.
package recfun
import common._
import scala.annotation.tailrec
object Balance {
def balance(chars: List[Char]): Boolean = {
@tailrec
def loop(chars: List[Char], open: Int): Boolean = {
chars match {
case Nil => open == 0
case '(' :: xs => loop(xs, open + 1)
case ')' :: xs => (open > 0) && loop(xs, open - 1)
case any => loop(chars.tail, open)
}
}
loop(chars, 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment