Scala: insert a new item at the specified position in the list

There is no built-in function or list method that allows the user to add a new item at a specific position in the list. I wrote a function that does this, but I'm not sure if it is a good idea to do it this way, although it works just fine:

def insert(list: List[Any], i: Int, value: Any) = { list.take(i) ++ List(value) ++ list.drop(i) } 

Using:

 scala> insert(List(1,2,3,5), 3, 4) res62: List[Any] = List(1, 2, 3, 4, 5) 
+5
source share
2 answers

Type Security

The most striking thing I see is the lack of security type / loss of type information. I would make the method generic in the list item type:

 def insert[T](list: List[T], i: Int, value: T) = { list.take(i) ++ List(value) ++ list.drop(i) } 

Style

If the body consists of only one expression, there is no need for curly braces:

 def insert[T](list: List[T], i: Int, value: T) = list.take(i) ++ List(value) ++ list.drop(i) 

Efficiency

@Marth's comment on using List.splitAt to avoid double-listing the list is also good:

 def insert[T](list: List[T], i: Int, value: T) = { val (front, back) = list.splitAt(i) front ++ List(value) ++ back } 

Interface

It might be convenient to be able to insert multiple values ​​at once:

 def insert[T](list: List[T], i: Int, values: T*) = { val (front, back) = list.splitAt(i) front ++ values ++ back } 

Interface, take 2

You can do this with the List extension method:

 implicit class ListWithInsert[T](val list: List[T]) extends AnyVal { def insert(i: Int, values: T*) = { val (front, back) = list.splitAt(i) front ++ values ++ back } } List(1, 2, 3, 6).insert(3, 4, 5) // => List(1, 2, 3, 4, 5, 6) 

Concluding observations

Note, however, that inserting in the middle of the list is simply not suitable for the list of minuses. You will be much better off with a (modified) linked list or dynamic array.

+26
source

You can also use xs.patch(i, ys, r) , which replaces the r elements of xs , starting with the i patch ys , using r=0 and doing ys singleton:

 List(1, 2, 3, 5).patch(3, List(4), 0) 
+15
source

All Articles