Scala - 递归比较函数

时间:2017-04-26 01:48:05

标签: scala recursion

我正在处理一个函数,以递归方式运行Int列表并返回一个布尔值,说明列表中的每个项目是否都是相同的数字。我已经在下面捅了一下,但它没有通过我正在运行的测试。这是我所拥有的,任何建议都非常感谢。谢谢!

def equalList (xs : List[Int]) : Boolean = {
def equalAux (xs:List[Int], value:Int) : Boolean = {
    xs match {
        case Nil => true
        case x :: xs if (x == value) => equalAux(xs, x)
        case x :: xs if (x != value) => false  
          }
}
  equalAux(xs, x)
}

2 个答案:

答案 0 :(得分:2)

正如您在评论中所说,您只需要确保列表不为空,这样您就可以为递归函数赋予初始值:

def equalList(xs: List[Int]): Boolean = {

  def equalAux (xs: List[Int], value: Int): Boolean = {
    xs match {
      case Nil => true
      case x :: xs if x == value => equalAux(xs, x)
      case x :: _ if x != value => false
    }
  }

  // Check to make sure the list has at least one item initially
  xs match {
    case Nil => true
    case head :: tail => equalAux(tail, head)
  }
}

println(equalList(List.empty))           // true
println(equalList(List(1)))              // true
println(equalList(List(1, 1, 1, 1)))     // true
println(equalList(List(1, 1, 1, 1, 2)))  // false
println(equalList(List(1, 2, 1)))        // false

答案 1 :(得分:0)

你需要一个递归函数吗?如果没有,我会使用Set作为一个技巧:

myList.toSet.size <= 1 // because empty list returns true. Else make it == 1

如果你确实需要递归,那么@Tyler回答是我也会给出的答案。