scala-library-next icon indicating copy to clipboard operation
scala-library-next copied to clipboard

Add updatedWith (and deleted) to sequences

Open charpov opened this issue 1 year ago • 1 comments

I recently found myself writing these extensions (with help from the Scala Users forum):

extension [A, CC[_]](seq: SeqOps[A, CC, CC[A]])
   def deleted(i: Int): CC[A]                                = seq.patch(i, Nil, 1)
   def updatedWith[B >: A](i: Int, f: A => Option[B]): CC[B] = seq.patch(i, f(seq(i)), 1)

to be used as:

List(A, X, C).deleted(1)                   // List(A, C)
List(A, X, C).updatedWith(1, _ => Some(B)) // List(A, B, C)

Someone there suggested this might make sense to be part of the Seq operations in a future version of the standard library. I was actually surprised to find them missing, especially since immutable maps do have an updatedWith method. I understand that sequences are not maps, but would there be much cost to add the methods to SeqOps with a default implementation based on patch?

charpov avatar Aug 14 '24 17:08 charpov