Last active
August 29, 2015 13:57
-
-
Save krisfoster/9555101 to your computer and use it in GitHub Desktop.
pascal.sc
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 | |
object session { | |
// Balances parens... | |
// | |
def balance(chars: List[Char]): Boolean = { | |
import scala.annotation.tailrec | |
@tailrec | |
def open(chars: List[Char], opened: Int): Boolean = | |
if (chars.isEmpty && opened == 0) | |
true | |
else if (chars.isEmpty && opened > 0) | |
false | |
else if (chars.head == ')') | |
if (opened > 0) | |
open(chars.tail, opened - 1) | |
else | |
false | |
else if (chars.head == '(') | |
open(chars.tail, opened + 1) | |
else | |
open(chars.tail, opened) | |
if (chars.isEmpty) | |
false | |
else | |
open(chars, 0) | |
} //> balance: (chars: List[Char])Boolean | |
import org.scalatest.Assertions._ | |
assert(balance("(if (zero? x) max (/ 1 x))".toList)) | |
assert(!balance("".toList)) | |
assert(balance("()".toList)) | |
assert(balance("(())".toList)) | |
assert(balance("(())()".toList)) | |
assert(balance("((()()()))".toList)) | |
assert(balance("(())".toList)) | |
assert(balance("some text((more text) and more) and yet more".toList)) | |
assert(!balance(")some text((more text) and more) and yet more".toList)) | |
assert(!balance("some) text((more text) and more) and yet more".toList)) | |
assert(!balance("some( text((more text) and more) and yet more".toList)) | |
assert(!balance("some text((more text) and more)( and yet more".toList)) | |
assert(!balance("(()))".toList)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment