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中将元素移动到列表的前面_Scala_Data Structures_Scala Collections - Fatal编程技术网

在Scala中将元素移动到列表的前面

在Scala中将元素移动到列表的前面,scala,data-structures,scala-collections,Scala,Data Structures,Scala Collections,我想知道是否有一种方法可以在一个列表中找到一个元素,并在Scala中将其移动到列表的前面?除了迭代列表,然后删除该元素,然后将其预先挂起到列表的前面之外,还有其他简单的方法吗?使用span如何: def moveToFront[A](y: A, xs: List[A]): List[A] = { xs.span(_ != y) match { case (as, h::bs) => h :: as ++ bs case _ => xs }

我想知道是否有一种方法可以在一个列表中找到一个元素,并在Scala中将其移动到列表的前面?除了迭代列表,然后删除该元素,然后将其预先挂起到列表的前面之外,还有其他简单的方法吗?

使用
span
如何:

def moveToFront[A](y: A, xs: List[A]): List[A] = {
  xs.span(_ != y) match {
    case (as, h::bs) => h :: as ++ bs
    case _           => xs
  }
}

考虑使用
partition
,其中感兴趣项目的多个匹配项被移动到头部,如下所示

implicit class RichList[A] (val a: List[A]) extends AnyVal {
  def toHead(e: A) = {
    val (l,r) = a.partition(_ != e)
    r ++ l
  }
}
因此,例如对于
val l=List(1,2,3,3,4,5,3)
我们有

l.toHead(3)
res: List(3, 3, 3, 1, 2, 4, 5)

l.toHead(7)
res: List(1, 2, 3, 3, 4, 5, 3)

这比我的答案要好。我将使它成为
p:A=>Boolean
,而不是
y:A
作为参数,这将使该方法更有用