is there a good way to "edit" an immutable list. I...
# announcements
w
is there a good way to "edit" an immutable list. I know Scala uses linked lists and prepends items (basically giving a new head) however I've found myself writing this like this.
Copy code
/**
 * Adds a new item to a new list, returning the new list.
 * @param item the item to add to the list
 * @return A new list with `item` added to the end.
 */
private fun <T> List<T>.add(item: T): List<T> {
    val copy = this.toMutableList()
    copy.add(item)
    return copy
}
which as far as I can see creates a new array list by copying the data.
r
And why do you want to edit an immutable list?
w
stepping back through a recursive stack each call adds an item to the list. However its good to keep the input different on each one.
r
Why don’t you use a MutableList if you want a mutable List?
w
I don't like mutating my input. Say an exception happened. and I look at the call stack. If its mutated I can't tell what the input was.
r
Then if you don’t want to mutate your input, you need to duplicate it
w
Yes I do. However I thought you may have a way similar to a scala.list. which means much less array copies.
I'm guessing no.
a
m
Are you sure Scala isn't creating a new list? Did they implement their own persistent collections in order to accomplish this? If they're just using the Java ones, then it's either mutating a list, or it's creating a new list exactly as you are. Otherwise, the head operation is creating a new list, and it's just syntax hiding it. For your code, you can just use
+
to create a new list that takes the first list, and a new element.
Copy code
val l = listOf(1)
l + 2    // [1,2]
l.toString() // [1]

val l2 = l + 3
l2.toString() // [1, 3]
👍 2
w
@Mike Yeah I'm pretty sure scala is implemented as a linked list always. Which means prepending creates a new element that links to the old list items. http://otfried.org/scala/list.html but I prefer your answer to my own code anyway.
m
Thank you for the link/info. Makes sense, and also explains the issues Scala has around interop with Java and Collections. Jetbrains decided to 'wrap' the Java ones for easier interop BUT loses the advantages of truly immutable listsl. But I do believe there is an initiative/issue/KEEP to introduce truly immutable lists to Kotlin.
j
this construct is not actually building a copy but v[3,2,1] would provide an altered result of the original v
Copy code
typealias Vect0r<Value> = Pair< /*Size*/ () -> Int, ( /*Key*/ Int) -> Value>

val<T> Vect0r<T>.size: Int get() = first.invoke()

@JvmName("vlike_Vect0r_IntArray3")
inline operator fun <reified T> Vect0r<T>.get(index: IntArray) = this.let { (a, b) ->
    index::size  to { ix: Int -> b(index[ix]) }
}
y9ou're paying for the IntArray and the lambda instead ofa new collection
w
@jimn good to know.