如何遍历包含scala中列表的tuple2?

时间:2017-03-10 10:30:11

标签: scala

我有一个函数从splitAt.How方法返回一个tuple2对象,从tuple2中获取单个对象(2个列表)? 这是我的功能

def isPalindrome(x:List[Int])={
   val long=x.length
   if (long%2==0){
      println("Liste paire")
   }
   else{
      x.splitAt((long/2).toInt)
   }
}
val spl=isPalindrome(List(1,2,3,4,6))
spl
res128: Any = (List(1, 2),List(3, 4, 6))
println(spl(1))
<console>:13: error: Any does not take parameters

更新:我试过了spl._1

println(spl._1)
<console>:13: error: value _1 is not a member of Any

3 个答案:

答案 0 :(得分:0)

您面临的问题是您的功能并不总是返回列表,数字或对象。结果取决于list.length是偶数还是奇数对。

如果可能的话,为了简单起见,从函数我总是期望相同的类型。

例如,名为isPalindrome的函数建议返回Boolean

def isPalindrome(x:List[Int]):Boolean = {
  x.equals(x.reverse)
}    

一旦您发现您的列表是回文,您就可以打印出结果。

if (isPalindrome(List(1,2,3,4,6))) {
   println("is Palindrome")
} else {
   println("not Palindrome")
}

或者拆分列表并根据需要打印结果。

val x = List(1,2,3,4,6)
val t2 = x.splitAt(x.size/2)

println(t2._1)
println(t2._2)

答案 1 :(得分:0)

Scala无法确定spl是元组还是Unit,因此其类型将被删除为Any。 你可以把它变成一个元组:

 spl.asInstanceOf[(List[Int],List[Int])]

或使用匹配:

spl.match{
    case s:(List[Int],List[Int])=>//Do something
    case _=>//Something else

答案 2 :(得分:0)

我不知道它会解决你的问题,但你想要的功能可以像下面这样实现:

def isPalindrome(x:List[Int])={
  val long=x.length
  if (long%2==0){
    println("Liste paire")
  }
  else{
    x.splitAt((long/2).toInt)
  }
}
val spl:Any=isPalindrome(List(1,2,3,4,6))
val splMatched = spl match {
  case (a , b) => (a, b)
  case _ => (Nil,Nil)
}
println(splMatched._1)