I am working on some code for balancing brackets, this question turned out to be the most useful for the algorithm.
I implemented it in my first language (PHP), but I am learning Scala and trying to convert the code.
Here is my PHP code:
function balanced($string) { return isBalanced($string, ""); } function isBalanced($chars, $stack) { if (!strlen($chars)) return empty($stack); switch ($chars[0]) { case '(': // prepend stack with '(', move to next character return isBalanced(substr($chars, 1), $chars[0] . $stack); case ')': // if '(' seen previously, shift stack, move to next character return !empty($stack) && isBalanced(substr($chars, 1), substr($stack, 1)); default: // do nothing to stack, move to next character return isBalanced(substr($chars, 1), $stack); } }
I tested this, it works. However, when I convert it to Scala, it does not work on balanced lines.
My Scala code:
object Main { def balance(chars: List[Char]): Boolean = { def balanced(chars: List[Char], stack: String): Boolean = { if (chars.isEmpty) stack.isEmpty else if (chars.head == ')') balanced(chars.tail, chars.head + stack) else if (chars.head == '(') !stack.isEmpty && balanced(chars.tail, stack.tail) else balanced(chars.tail, stack) } balanced(chars, "") } }
I appreciate that this is not the best Scala code, but I'm just getting started. Some tests:
balance("(if (0) false (x))".toList) - fails balance("profit and loss (P&L).\n(cashflow)".toList) - fails balance(":)".toList) - passes balance(")(()".toList) - passes
. All of these tests pass the equivalent of PHP. What have I done wrong in my Scala implementation?