Trying to remove the first element of a list if it is zero (not really, but for the purpose of an example).
Given a list:
val ns = List(0, 1, 2)
Deleting the first zero could be done by dropping the first matches for zero:
List(0, 1, 2).dropWhile(_ == 0)
res1: List[Int] = List(1, 2)
Or you could delete everything that's not a zero.
List(0, 1, 2).filter(_ > 0)
res2: List[Int] = List(1, 2)
The problem with these is when the list has multiple zeroes. The previous solutions don't work, because they delete too many zeroes:
List(0, 0, 1, 2, 0).filter(_ > 0)
res3: List[Int] = List(1, 2)
List(0, 0, 1, 2, 0).dropWhile(_ == 0)
res4: List[Int] = List(1, 2, 0)
Is there an existing function for this?
I also think pattern matching is the best option for readability and performance (I tested and the pattern matching code from OP actually performs better than simple if ... else ....).
List(0, 0, 1, 2, 0) match {
case 0 :: xs => xs
case xs => xs
}
res10: List[Int] = List(0, 1, 2, 0)
And, no, there's no simple built in function for this.
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