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

问题描述 投票:0回答:4

我正在尝试使用以下函数交换List中的前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))

这有效。但是,如果我尝试包含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]?

我需要返回List(20,10,30)。怎么解决这个?

scala
4个回答
5
投票

显然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)

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)

2)使用List附加:+

scala> List(1, 2, 3) :+ 100
res2: List[Int] = List(1, 2, 3, 100)

3)concat列表使用++,与in haskell相同

scala> List(1, 2, 3) ++ List(4, 5, 6)
res3: List[Int] = List(1, 2, 3, 4, 5, 6)

5
投票

好吧,虽然prayagupd解决方案工作,并清楚地解释了问题(应该是接受的答案恕我直言)。

我认为值得为这个问题分享一个“更好”的解决方案,因为连接列表很昂贵,最好只为它们预先添加元素。

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

3
投票

你需要++而不是+:,因为后者是单个元素。


3
投票

最简单的实现是这样的:

def swap_list(a: List[Int]): List[Int] =
  a match {
    case x :: y :: tail => y :: x :: tail
    case _ => a
  }
© www.soinside.com 2019 - 2024. All rights reserved.