Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
scala-交换列表中的前2个元素_Scala - Fatal编程技术网

scala-交换列表中的前2个元素

scala-交换列表中的前2个元素,scala,Scala,我正在尝试使用下面的函数交换列表中的前两个元素 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)) 这很有效。但是,如果我尝试包含rest,我会得到如

我正在尝试使用下面的函数交换列表中的前两个元素

  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))
这很有效。但是,如果我尝试包含
rest
,我会得到如下错误

case List(x,y,rest @ _*) =>  List(y,x) +: rest
下面的错误

Error:(27, 50) type mismatch;
found   : Seq[Any]
required: List[Int]
case List(x,y,rest @ _*) =>  List(y,x) +: rest
在定义中指定函数结果类型时,为什么会在错误消息中得到Seq[Any]


我需要返回列表(20,10,30)。如何解决这个问题?

显然scala
列表中的运算符令人困惑。您需要使用
++
,

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)
操作员列表的汇总
操作员,

1)使用
+:
::

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)
scala> List(1, 2, 3) :+ 100
res2: List[Int] = List(1, 2, 3, 100)
2)使用
:+

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)
scala> List(1, 2, 3) :+ 100
res2: List[Int] = List(1, 2, 3, 100)
3)使用
++
的concat列表,与


您需要
++
而不是
+:
,因为后者适用于单个元素。

好吧,而prayagupd解决方案有效,并清楚地解释了问题(应该是IMHO接受的答案)

我认为有必要为这个问题分享一个“更好”的解决方案,因为串联列表很昂贵,所以最好只在列表前面加上元素

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).

最简单的实现是:

def swap_list(a: List[Int]): List[Int] =
  a match {
    case x :: y :: tail => y :: x :: tail
    case _ => a
  }

当我在我发布的代码中删除函数中的返回类型时,它起了作用,但结果是
List(List(20,10),30)
。你能解释一下吗?这意味着你在预编
List(20,10)+:List(30)
,它返回的
List[Any]
不好。使用
++
来压缩列表,请参见上面的示例