" Exception in thread "main" java.util.NoSuchElementException: head of empty list " error and more in Scala

compiler-errors, eclipse, list, scala

Solution

You need to check whether your `List` is empty before you call `head`, `match` is probably the best way to do this:

  def balance(chars: List[Char]) = {

    def recursbalance(chars: List[Char], stack: Int): Int = chars match {
      case Nil => stack
      case ')' :: tail => recursbalance(tail, stack - 1)
      case '(' :: tail => recursbalance(tail, stack + 1)
      case x :: tail => recursbalance(tail, stack)
    }
    recursbalance(chars, 0) == 0;
  }

I have changed your method a little to remove the `MutableInt` and use an `Int` directly internally.

I ran a quick check:

  println(balance("())".toList));
  println(balance("(())".toList));

Output

false
true

Problem

I wrote a recursive parentheses balancing function and there doesnt seem to be any errors in the code but when I run it I get a lot of errors. I wrote the function with a call like this: ``` if(balance("blarg(arg)".toList)) println("true!") else println("false") ``` and a definition like this: ``` def balance(chars: List[Char]): Boolean ={ implicit class MutableInt(var value: Int) { def inc() = { value+=1 } def dec() = { value-=1 } } var stack: Int = 0 def recursbalance(chars: List[Char], stack: Int): Boolean= { if ((chars.head: Char) == "(".toList) stack.inc() else if ((chars.head: Char) == ")".toList) stack.dec() if (stack<0) false if (chars.isEmpty: Boolean) if (stack == 0) true else false recursbalance(chars.tail: List[Char], stack: Int) } recursbalance(chars: List[Char], stack: Int) } ``` I'm getting these errors: ``` Exception in thread "main" java.util.NoSuchElementException: head of empty list at scala.collection.immutable.Nil$.head(List.scala:337) at scala.collection.immutable.Nil$.head(List.scala:334) at recfun.Main$.recursbalance$1(Main.scala:45) at recfun.Main$.balance(Main.scala:55) at recfun.Main$.main(Main.scala:16) at recfun.Main.main(Main.scala) ``` How do I fix? sorry for any noobness, I'm new to Scala. I tried replacing my recursive calls with this: ``` if (chars.isEmpty: Boolean) { if (stack == 0) true else false } else recursbalance(chars.tail: List[Char], stack: Int) ``` but i still got all the errors..

Original source