Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a new element in a specified position of a list

Tags:

scala

There is no built-in function or a method of a List that would allow user to add a new element in a certain position of a List. I've wrote a function that does this but I'm not sure that its a good idea to do it this way, even though it works perfectly well:

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

Usage:

scala> insert(List(1,2,3,5), 3, 4)
res62: List[Any] = List(1, 2, 3, 4, 5)
like image 297
HeeL Avatar asked Jun 24 '15 21:06

HeeL


1 Answers

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

List(1, 2, 3, 5).patch(3, List(4), 0)
like image 132
Ben Reich Avatar answered Oct 04 '22 02:10

Ben Reich