Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace element in List with scala

Tags:

replace

scala

How do you replace an element by index with an immutable List.

E.g.

val list = 1 :: 2 ::3 :: 4 :: List()

list.replace(2, 5)
like image 969
Berlin Brown Avatar asked Feb 21 '11 04:02

Berlin Brown


4 Answers

If you want to replace index 2, then

list.updated(2,5)    // Gives 1 :: 2 :: 5 :: 4 :: Nil

If you want to find every place where there's a 2 and put a 5 in instead,

list.map { case 2 => 5; case x => x }  // 1 :: 5 :: 3 :: 4 :: Nil

In both cases, you're not really "replacing", you're returning a new list that has a different element(s) at that (those) position(s).

like image 54
Rex Kerr Avatar answered Oct 24 '22 05:10

Rex Kerr


In addition to what has been said before, you can use patch function that replaces sub-sequences of a sequence:

scala> val list = List(1, 2, 3, 4)
list: List[Int] = List(1, 2, 3, 4)

scala> list.patch(2, Seq(5), 1) // replaces one element of the initial sequence
res0: List[Int] = List(1, 2, 5, 4)

scala> list.patch(2, Seq(5), 2) // replaces two elements of the initial sequence
res1: List[Int] = List(1, 2, 5)

scala> list.patch(2, Seq(5), 0) // adds a new element
res2: List[Int] = List(1, 2, 5, 3, 4)
like image 43
Vasil Remeniuk Avatar answered Oct 24 '22 03:10

Vasil Remeniuk


You can use list.updated(2,5) (which is a method on Seq).

It's probably better to use a scala.collection.immutable.Vector for this purpose, becuase updates on Vector take (I think) constant time.

like image 12
Ken Bloom Avatar answered Oct 24 '22 04:10

Ken Bloom


You can use map to generate a new list , like this :

@ list
res20: List[Int] = List(1, 2, 3, 4, 4, 5, 4)
@ list.map(e => if(e==4) 0 else e)
res21: List[Int] = List(1, 2, 3, 0, 0, 5, 0)
like image 2
damon-lin Avatar answered Oct 24 '22 04:10

damon-lin