Kotlin prepend element
I am searching for Kotlin alternative to:(cons 1 '(2 3))
in lisp or1 : [2, 3]
in haskell or1 :: List(2, 3)
in scala,
(which all result in sth like [1, 2, 3])
so I can prepend an element to a List<T>
(or any other list you can offer).
It will also be fine if one could provide O(1) head
and tail
Kotlin alternatives (I've found just first()
)
Solution 1:
I think the easiest would be to write:
var list = listOf(2,3)
println(list) // [2, 3]
list = listOf(1) + list
println(list) // [1, 2, 3]
There is no specific tail
implementation, but you can call .drop(1) to get the same. You can make this head\tail
more generic by writing these extension properties:
val <T> List<T>.tail: List<T>
get() = drop(1)
val <T> List<T>.head: T
get() = first()
Then:
val list = listOf(1, 2, 3)
val head = list.head
val tail = list.tail
Some more info: Kotlin List tail function
Solution 2:
Any class which implements Deque
will suitable for you, for example LinkedList
:
val linkedList = LinkedList(listOf(2, 3))
linkedList.push(1)
println(linkedList) // [1, 2, 3]
Creating lists throught constructor LinkedList(listOf(2, 3))
in many places can be annoying, so feel free to write factory method:
fun <T> linkedListOf(vararg elements: T): LinkedList<T> {
return LinkedList<T>(elements.toList())
}
// Usage:
val list = linkedListOf(2, 3)
list.push(1)
println(list) // [1, 2, 3]
Solution 3:
Simple, just wrap the element to prepend in a List
and then use the +
operator (or List.plus()
) to concatenate the two Lists
:
val list1 = listOf(2, 3) // [2, 3]
val list2 = listOf(1) + list1 // [1, 2, 3]
For your second question, in Kotlin 1.2 there are:
List.first()
List.last()
Both are O(1)
Solution 4:
This could be done easily with extension functions as below
Prepending element
fun <T> MutableList<T>.prepend(element: T) {
add(0, element)
}
Prepending list
fun <T> MutableList<T>.prependAll(elements: List<T>) {
addAll(0, elements)
}
Solution 5:
If you do that often in your code for some reason, consider adding an extension operator method such as:
operator fun <T> T.plus(tail: List<T>): List<T> {
val list = ArrayList<T>(1 + tail.size)
list.add(this)
list.addAll(tail)
return list
}
Then your code could work Scala-like: 1 + listOf(2, 3)
Another way to achieve the same behaviour, shorter but sacrifices some memory:
operator fun <T> T.plus(tail: List<T>): List<T> {
return mutableListOf(this).apply {
addAll(tail)
}
}