Scala List [Char]为空但不返回true

时间:2013-04-08 02:20:29

标签: scala recursion

我有以下代码(这是我的课程作业)

def balance(chars: List[Char]): Boolean = {
  def innerBalance(chars: List[Char], count: Int): Boolean = {
    if (chars.isEmpty) count == 0
    if (chars.head == '(') innerBalance(chars.tail, count+1)
    if (chars.head == ')') (count > 0) && innerBalance(chars.tail, count-1)
    innerBalance(chars.tail, count)
  }

  innerBalance(chars, 0)
} 

据我所知,这与炖菜的答案非常相似Scala way to program bunch of if's 但我不知道为什么声明

if (chars.isEmpty) count == 0
总是假的。

如果我像这样进行测试

balance("".toList)

它只是抛出异常。

感谢您的帮助。 的问候,

3 个答案:

答案 0 :(得分:4)

在Scala中,你永远不应该使用return,而是编写表达式。上面代码的主要问题是你没有使用if表达式,即你省略了else部分,因此编译器推断Unit(Java的void,这意味着“没有“得到回报”。

由于您的案例有多种选择,我建议您使用匹配表达式:

chars match {
  case '(' :: Nil => ...
  case ')' :: Nil => ...
  case Nil        => count == 0
  case _          => innerBalance(chars.tail, count)
}

答案 1 :(得分:2)

添加到Huw's answer,您还可以使用模式匹配来使其更优雅:

      def innerBalance(chars: List[Char], count: Int): Boolean = chars match {
          case _ if count < 0  => false
          case Nil             => count == 0
          case '(' :: rest     => innerBalance(rest, count + 1)
          case ')' :: rest     => innerBalance(rest, count - 1)
          case _ :: rest       => innerBalance(rest, count)
      }

答案 2 :(得分:0)

这样的街区
{
  if (a) b
  c
}
如果b为真,

a,然后始终执行c。如果您希望c仅在a为假时发生,则需要使用else

{
  if (a) b
  else c
}
相关问题