user2293385
user2293385

Reputation:

Creating a Map from Tuples in Scala

I am new to function programming language and need help for one of my problem.

I need to create a map between two tuple of sequences :

A = tuple1(tuple1(tuple1(x,y),z),a)

B = tuple2(tuple2(tuple2(1,2),3),4)

now i need something like below :

C = ((x,1),(y,2),(z,3),(a,4)) and if i search for say x then i need to get 1 ;

The number of tuple occurrences are unknown but both the tuple structure will be similar. I could not understand and map the solution for similar kind of questions in stackoverflow. So solution with explanation will be helpful

Upvotes: 0

Views: 270

Answers (1)

Jasper-M
Jasper-M

Reputation: 15086

I think this does the (ugly) trick.

def toMap(x: (Any,String), y: (Any,Int)): Map[String, Int] = {
  @tailrec
  def rec(x: (Any,String), y: (Any,Int), map: Map[String, Int]): Map[String, Int] =
    x match {
      case (a: String, b) => 
        val (c: Int, d) = y
        map ++ Map(a -> c, b -> d)
      case (a: (Any,String), b) => 
        val (c: (Any,Int), d) = y
        rec(a, c, map ++ Map(b -> d))
    }
  rec(x, y, Map.empty[String, Int])
}

Assuming you want to use it like this:

scala> val a = ((("x","y"),"z"),"a")
a: (((String, String), String), String) = (((x,y),z),a)

scala> val b = (((1,2),3),4)
b: (((Int, Int), Int), Int) = (((1,2),3),4)

scala> toMap(a,b)
res1: Map[String,Int] = Map(a -> 4, z -> 3, x -> 1, y -> 2)

Upvotes: 1

Related Questions