Scala 从字符列表中获取括号

Scala 从字符列表中获取括号,scala,recursion,Scala,Recursion,我想实现一个函数,从给定的字符列表中检索所有括号 def getParentheses(chars: List[Char]): String = { if (chars.isEmpty) "" else { val head = chars.head.toString if (head == "(" || head == ")") head + getParentheses(chars.tail) } } 但我在第五行不断收到Scala ID

我想实现一个函数,从给定的字符列表中检索所有括号

def getParentheses(chars: List[Char]): String = {
    if (chars.isEmpty) ""
    else {
      val head = chars.head.toString
      if (head == "(" || head == ")") head + getParentheses(chars.tail)
    }
  }
但我在第五行不断收到Scala IDE关于类型不匹配的错误,但这一行看起来很好

if(head==”(“| | head==”)head+get圆括号(chars.tail)

那我该怎么修呢


谢谢你的帮助

使用List.collect函数作为PartialFunction:

val isParentheses: PartialFunction[Char, Char] = { 
  case ch: Char if(ch == '(' || ch == ')' ) => ch  
}
val onlyParentheses = listOfchars.collect(isParentheses)
注意:我没有测试这个解决方案,尽管它应该可以工作

编辑

很抱歉,我没有注意到您需要修复代码。我认为问题部分在于

head+get圆括号


函数返回字符串,头是Char。您确定可以使用
+
将字符连接到字符串吗

错误指出,
get圆括号
需要一个
字符串
作为返回值,但您的函数返回
单位
。Scala函数的最后一行是返回值,在您的例子中,它是一个
if
,返回
Unit
。如果,则必须重构第二个
。下面是我将如何使用模式匹配来实现它

def getParentheses(chars: List[Char]): String = chars match {
  case h::t if h == '(' || h == ')' => h + getParentheses(t)
  case h::t => getParentheses(t)
  case Nil => ""
}
不过,使用
filter
可能更为惯用

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

但是这一行不是把列表的第一个元素转换成一个字符吗
val head=chars.head.toString
@Brian是对的。第二个
(如果
)并非详尽无遗。如果此部分
head==”(“|head==”)
的计算结果为false,会发生什么情况?那么你的方法不会返回任何东西。换句话说,当你写它返回字符串时,它返回
Unit
。现在我明白了,当一个函数应该返回一些东西时,它应该不惜一切代价返回。因此,这里有一个简单的
else
解决了我的问题,但是@Brian solution更简洁,通过使用filter方法在一行中完成工作。这个filter方法在一行中解决了问题,实际上,我喜欢它!非常感谢。