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()
)
You can use add(index, value) method.
To add a single element to a list or a set, use the add() function. The specified object is appended to the end of the collection. addAll() adds every element of the argument object to a list or a set.
We can insert an item to an ArrayList using the add() function provided by the Kotlin library. In this example, we will be creating two lists: one is "myMutableList" which is a collection of mutable data types, and the other one is "myImmutableList" which is a collection of immutable data types.
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With