Skip to content

Instantly share code, notes, and snippets.

@vdupain
Created April 5, 2013 14:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vdupain/5319579 to your computer and use it in GitHub Desktop.
Save vdupain/5319579 to your computer and use it in GitHub Desktop.
Exercise 2: Parentheses Balancing
object balance {
def balance(chars: List[Char]): Boolean = {
def loop(acc: Int, list: List[Char]): Int =
if (list.isEmpty) acc
else if (list.head == '(') loop(acc + 1, list.tail)
else if (list.head == ')' && acc > 0) loop(acc - 1, list.tail)
else if (list.head == ')' && acc <= 0) -1
else loop(acc, list.tail)
loop(0, chars) == 0
}
balance("()".toList)
balance(")(".toList)
balance("xxx".toList)
balance(List())
balance("".toList)
balance("(if (zero? x) max (/ 1 x))".toList)
balance("I told him (that it's not (yet) done).\n(But he wasn't listening)".toList)
balance(":-)".toList)
balance("())(".toList)
balance("(".toList)
}
@Justintc217
Copy link

This strategy is so much simpler than mine cries dramatically

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment