Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin prepend element

I am searching for Kotlin alternative to:
(cons 1 '(2 3)) in lisp or
1 : [2, 3] in haskell or
1 :: 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())

like image 575
Columpio Avatar asked Mar 19 '17 21:03

Columpio


People also ask

What is the best way to put an element at the top of a list?

You can use add(index, value) method.

How do I add elements from one list to another in Kotlin?

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.

How do I add an element to an ArrayList in Kotlin?

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.


2 Answers

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

like image 188
Strelok Avatar answered Oct 09 '22 09:10

Strelok


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] 
like image 33
Ruslan Avatar answered Oct 09 '22 08:10

Ruslan