title: Algorithm to check matching parenthesis
body: <p>This relates to the Coursera Scala course so I want to directly ask you NOT to give me the answer to the problem, but rather to help me debug why something is happening, as a direct answer would violate the Coursera honor code.</p>
  
  <p>I have the following code:</p>
  
  <pre><code>    def balance(chars: List[Char]): Boolean = {
      val x = 0
      def loop(list: List[Char]): Boolean = {
        println(list)
  
        if (list.isEmpty) if(x == 0) true
        else if (list.head == '(') pushToStack(list.tail)
        else if (list.head == ')') if(x &lt;= 0) false else decreaseStack(list.tail)
        else loop(list.tail)
  
  
        true
      }
  
      def pushToStack(myList: List[Char]) { x + 1; loop(myList)}
  
      def decreaseStack(myList: List[Char]) { x - 1; loop(myList)}
  
      loop(chars)
    }
  </code></pre>
  
  <p>A simple explanation:</p>
  
  <p>If the code sees a "(" then it adds 1 to a variable. If it sees a ")" then it first checks whether the variable is equal to or smaller than 0. If this is the case, it returns false. If the value is bigger than 0 then it simply decreases one from the variable.</p>
  
  <p>I have tried running the following:</p>
  
  <pre><code>if(balance("This is surely bad :-( ) (".toList)) println("balanced") else println("not balanced");
  </code></pre>
  
  <p>Clearly this is not balanced, but my code is returning balanced. </p>
  
  <p>Again: I am not asking for help in writing this program, but rather help in explained why the code is returning "balanced" when clearly the string is not balanced</p>
  
  <p>--EDIT--</p>
  
  <pre><code>  def balance(chars: List[Char]): Boolean = {
  
      val temp = 0;
  
     def loop(list: List[Char], number: Int): Boolean = {
        println(list)
  
        if (list.isEmpty) if(number == 0) true
        else if (list.head == '(') loop(list.tail, number + 1)
        else if (list.head == ')') if(number &lt;= 0) false else loop(list.tail, number - 1)
        else loop(list.tail,number)
  
  
        true
      }
  
  
      loop(chars,0)
    }
  </code></pre>
  
  <p>^^ Still prints out balanced </p>