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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With