Question

I wanted to implement a function to retrieve all parentheses from a given list of chars

def getParentheses(chars: List[Char]): String = {
    if (chars.isEmpty) ""
    else {
      val head = chars.head.toString
      if (head == "(" || head == ")") head + getParentheses(chars.tail)
    }
  }

but I keep getting an error from the Scala IDE on the fifth line about a type mismatch but the line looks fine to me

if (head == "(" || head == ")") head + getParentheses(chars.tail)

So how can I fix it?

Thanks for your help!

Was it helpful?

Solution

The error is stating that getParentheses expects a String as return value but your function returns Unit. The last line in a Scala function is the return value which in your case is an if which returns Unit. You would have to refactor the second if. Here's how I would do it with pattern matching.

def getParentheses(chars: List[Char]): String = chars match {
  case h::t if h == '(' || h == ')' => h + getParentheses(t)
  case h::t => getParentheses(t)
  case Nil => ""
}

It's probably more idiomatic to do it with filter though.

scala> List(')', 'a', ')').filter(x => x == ')' || x == '(') 
res0: List[Char] = List(), ))

OTHER TIPS

Make use of List.collect function that takes PartialFunction:

val isParentheses: PartialFunction[Char, Char] = { 
  case ch: Char if(ch == '(' || ch == ')' ) => ch  
}
val onlyParentheses = listOfchars.collect(isParentheses)

Note I have not tested this solution although it should work.

EDIT.

Sorry I haven't noticed you want your code fixed. I think the problem lies in part

head + getParentheses

your function returns String and head is Char. Are you sure you can concatenate Char to String using + ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top