How about Array/List update extension

Hi
Recently I use much an extension, I think maybe many people often use it too. Is it suitable to add it to std library?

inline fun ByteArray.update(block: (data: Byte, idx: Int) -> Byte) {
    for (i in 0 until this.size) {
        this[i] = block(this[i], i)
    }
}

It already exists. It is called mapIndexed :wink:

It is close, but I realy want a in-place operation

I don’t understand what do you mean by in-place? Do you mean inline? The stdlib version is a inline function so I don’t see the difference.

Ok, now I understand what you mean. You want a map/mapIndexed which modifies the original list/array/etc.
I think I might support this addition. There are reasons for and against it.

Pro:

  1. Updating a list multiple other places reference without having to share update the references of the other places.
  2. This would probably be more memory efficient, especially for long lists, as you no longer need to hold 2 copies in memory
  3. If the original list is no longer needed this would be less work for the garbage collector ( so minor performance increase)?

Contra:

  1. Could lead to misunderstandings in comparison to map as people who are coming from languages without functional programing aspects might not be used to the terminology and therefor lead to bugs which might be very hard to find

The more I think about it the more I like adding this to the std-lib. I would be interested if there are any other reasons for or against it as I can’t think of them right now.

Not everything has to go into the standard library. How about you put it into a new library yourself?

Common Lisp has this functionality, called MAP-INTO. CLHS: Function MAP-INTO

I think that’s a pretty fitting name, and one I’d use if I needed to implement such function.

2 Likes