2017-04-26 124 views
0

我正在处理函数以递归方式运行一个Ints列表并返回一个布尔值,指出列表中的每个项目是否是相同的数字。我在下面刺了一下,但没有通过我正在运行的测试。这是我得到的,任何建议都非常感谢。谢谢!斯卡拉 - 递归比较函数

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) 
} 
+0

你能举一个例子说明这是失败吗? – Tyler

+0

现在我实际上遇到了一个编译错误,当我打电话给我的辅助功能,说“找不到:值x”。我尝试将其更改为“xs.head”,但这不适用于空列表。我相信那是以前的失败案例。 – Polyphase29

回答

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 
+0

啊!这工作!谢谢一堆。 – Polyphase29

0

你需要一个递归函数?如果没有,我会用设置为一招:

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

如果你确实需要递归,然后@Tyler答案是答案,我也给。