Reputation: 5659
I was wondering if there is a way to find an element in a list and move it to the front of the list in Scala? Is there any easy way to do this other than iterating over the list, then removing that element and then pre-pending it to the front of the list?
Upvotes: 4
Views: 2063
Reputation: 20415
Consider the use of partition
where multiple occurrences of the item of interest are moved to the head, like this,
implicit class RichList[A] (val a: List[A]) extends AnyVal {
def toHead(e: A) = {
val (l,r) = a.partition(_ != e)
r ++ l
}
}
Hence for example for val l = List(1,2,3,3,4,5,3)
we have that
l.toHead(3)
res: List(3, 3, 3, 1, 2, 4, 5)
l.toHead(7)
res: List(1, 2, 3, 3, 4, 5, 3)
Upvotes: 0
Reputation: 23633
How about using span
?:
def moveToFront[A](y: A, xs: List[A]): List[A] = {
xs.span(_ != y) match {
case (as, h::bs) => h :: as ++ bs
case _ => xs
}
}
Upvotes: 10