Created
September 18, 2013 07:31
-
-
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.
This file contains 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
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