我正在尝试使用以下功能交换列表中的前2个元素。
def swap_list(a:List[Int]):List[Int]={
a match {
case x::y::Nil => List(y,x)
case List(x,y,rest @ _*) => List(y,x)
case _ => a
}
}
swap_list(List(10,20,30))
Run Code Online (Sandbox Code Playgroud)
这可行。但是,如果我尝试包含,rest则会出现类似以下错误
case List(x,y,rest @ _*) => List(y,x) +: rest
Run Code Online (Sandbox Code Playgroud)
错误如下
Error:(27, 50) type mismatch;
found : Seq[Any]
required: List[Int]
case List(x,y,rest @ _*) => List(y,x) +: rest
Run Code Online (Sandbox Code Playgroud)
在定义中指定函数结果类型时,为什么在错误消息中得到Seq [Any]?
我需要返回List(20,10,30)。如何解决呢?
显然,scala List中的运算符令人困惑。您需要使用来合并列表++,
def swap_list(a:List[Int]):List[Int]={
a match {
case x::y::Nil => List(y,x)
case List(x,y,rest @ _*) => List(y,x) ++ rest
case _ => a
}
}
val newList = swap_list(List(10, 20, 30))
println(newList) //List(20, 10, 30)
Run Code Online (Sandbox Code Playgroud)
List运营商摘要,
1)优先List使用+:或::
scala> 1000 +: List(1, 2, 3)
res1: List[Int] = List(1000, 1, 2, 3)
scala> 1000 :: List(1, 2, 3)
res4: List[Int] = List(1000, 1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
2)附加List使用:+
scala> List(1, 2, 3) :+ 100
res2: List[Int] = List(1, 2, 3, 100)
Run Code Online (Sandbox Code Playgroud)
3)使用的concat列表++,与haskell中的相同
scala> List(1, 2, 3) ++ List(4, 5, 6)
res3: List[Int] = List(1, 2, 3, 4, 5, 6)
Run Code Online (Sandbox Code Playgroud)
好吧,尽管祈祷解决方案有效,并且清楚地说明了问题(并且应该是恕我直言的答案)。
我认为值得分享一个“更好”的解决方案,因为连接列表很昂贵,因此最好在元素之前添加元素。
def swapList[T](l: List[T]): List[T] = l match {
case Nil => Nil
case x :: Nil => x :: Nil
case x :: y :: xs => y :: x :: xs
}
swapList(List(10,20,30)) // res0: List[Int] = List(20, 10, 30).
Run Code Online (Sandbox Code Playgroud)