title: Scala Removing Item from List - Comparison of Methods
body: <p>I am starting the Scala programming course on <a href="https://www.coursera.org/course/progfun" rel="nofollow noreferrer">Coursera</a>, coming from 2 years experience with Java/Python/C#.</p>
  
  <p>I am working through a problem where you must check to see if a list of characters has balanced paranthesis.</p>
  
  <pre><code>/**
  * Exercise 2
  */
  def balance(chars: List[Char]): Boolean = {
  
  def recursiveBalance(chars: List[Char]): Boolean = {
    if (!chars.contains('(') &amp;&amp; !chars.contains(')')) true
    else {
      val openIndex = chars.indexOf('(')
      if (openIndex == -1) false
      else {
        val chars2 = dropFirstMatch(chars, '(')
        val closeIndex = chars2.indexOf(')')
        if(closeIndex == -1 || openIndex &gt; closeIndex) false
        else recursiveBalance(dropFirstMatch(chars2, ')'))
      }
    }
  }
  
  def remove(index: Int, list: List[Char]): List[Char] = {
    list.take(index) ++ list.drop(index)
  }
  
  def dropFirstMatch[A](ls: List[A], value: A): List[A] = {
    val index = ls.indexOf(value)  //index is -1 if there is no match
    if (index &lt; 0) {
      ls
    } else if (index == 0) {
      ls.tail
    } else {
      // splitAt keeps the matching element in the second group
      val (a, b) = ls.splitAt(index)
      a ++ b.tail
    }
  }
  recursiveBalance(chars)
  </code></pre>
  
  <p>}</p>
  
  <p>So this solution is working (if a little ugly). As part of the solution I attempted to remove an object from a list at a specific index. I've learned that in Scala Lists are immutable.</p>
  
  <p>My attempt at doing this was to provide the index, the list, and use <a href="https://stackoverflow.com/questions/18847249/how-to-remove-an-item-from-a-list-in-scala-having-only-its-index">this example</a>, which is the <code>remove</code> function. This works in the REPL, I made a list, ran the function and a new list was returned without the specified index.</p>
  
  <p>But this did not work in my <code>balance</code> solution. Everytime the list was returned it was unchanged, causing infinite recursion. Eventually I stumbled on <a href="http://alvinalexander.com/scala/how-to-delete-elements-from-list-listbuffer-scala-cookbook" rel="nofollow noreferrer">this article</a> and borrowed their <code>dropFirstMatch</code> function, and upon substituting it, bam, working solution.</p>
  
  <p>I am very new to Scala, and I must be overlooking something - can someone point out what it might be?</p>