UGeorge UGeorge - 1 year ago 69
Scala Question

Some Workaround with scala map() and list

So, i got a list of tuples where tuple is pair of Int and

. I need to add one item in inner list to accomplish i tried to use map function and did like this

val list = List((7, List(2,4,18)), (10,List (4,8,12)), (12, List (5, 9, 13))) => mapFunction(e,16,10))

Above i want to insert in tuple with first value 10, in its list 16. Here is mapFunction :

def mapFunction(element: (Int, List[Int]), i: Int, fileID: Int) : (Int, List[Int]) = {
if (element._1 == fileID) {
val list2 = element._2 :+ i
(element._1, list2)

list 2 contains added value, but in the original list still unchanged. Is there some workaround?

Answer Source

Does this get at what you're after?

val lstA = List((7, List(2,4,18)), (10,List (4,8,12)), (12, List (5, 9, 13)))
val lstB ={case (n,l) if n == 10 => (n, l :+ 16) ;case e => e}

A map call on the first List won't modify the list. It will create a new, modified, list.

To wrap it in a function might go like this.

// returns new List
def f(lst: List[(Int, List[Int])], i: Int, fileID: Int) : List[(Int, List[Int])] ={case (n,l) if n == fileID => (n, l :+ i) ;case e => e}


It strikes me that if the Int part of your (Int,List) tuple is a "fileID" then it is probably required to be unique across the entire list of tuples, i.e. you'd never have List( (10,List(2,4)), (10,List(3,5)) ). If that's the case then why not use a Map instead of a tuple? That would guarantee uniqueness and simplify accessing the inner lists. You might use a mutable Map to make data insertion easier.

import collection.mutable.{Map => MMap}

def insert(m: MMap[Int, List[Int]], fileID: Int, n: Int): Unit = {
  val newList: List[Int] = m.getOrElseUpdate(fileID, List()) :+ n
  m.update(fileID, newList)

So if you have a dataset like this...

val index: Map[String, MMap[Int, List[Int]]] =
  Map("key1" -> MMap(7 -> List(2,4,18), 10 -> List(4,8,12), 12 -> List(5, 9, 13))
    , "key2" -> MMap(8 -> List(2,4,18))) can update it like so.

insert(index("key2"), 19, fileID = 9)
insert(index("key1"), fileID = 10, 16)

Now the dataset looks like this.

Map(key1 -> Map(7 -> List(2,4,18), 10 -> List(4,8,12,16), 12 -> List(5,9,13))
  , key2 -> Map(8 -> List(2,4,18), 9 -> List(19)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download