Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving an element to the front of a list in Scala

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?

like image 433
jcm Avatar asked Dec 26 '22 06:12

jcm


1 Answers

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
  }
}
like image 168
jonderry Avatar answered Jan 01 '23 16:01

jonderry