Deleting/replacing inside sequences

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?

2 Likes

This looks convenient.

But it has an issue regarding runtime cost: This could be very expensive methods when used on a linear sequence instead of on an indexed one.

But I guess the underlying patch has already this issue. So makes not much difference. Just needs to be documented properly I think.

I’ll welcome it.

(Isn’t here some thread about proposals for the next std. lib somewhere? Or was it a issue on GitHub that collects proposals? I think this here belongs on this list.)

Yes, many of the methods common to all collections have poor performance on some types, something to always be aware of (I keep reminding students). The issue is not so much indexed vs linear but the copying needed (e.g., it will be inefficient even on immutable.ArraySeq). Still, it’s no worse than append, or init, or some of the existing methods.

That rings a bell. If someone can post the link, I’ll move my message there.

I think it was this here:

But not sure there is also some other place.

Related:

1 Like

I added an issue to the “ghost” repository.

Let’s see what happens.

I’m also somehow clueless what’s the current state of the lib-next initiative.

1 Like