0

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

5
  • 5
    I think the proper solution is to avoid creating nested tuple structures like this in the first place. They aren't easy to work with. Create lists instead and you can use zip with toMap to get what you want. Commented Jun 27, 2014 at 22:06
  • Can you explain a bit more what you are trying to achieve? Is it essential that you use nested tuples (or even nested lists)? Commented Jun 27, 2014 at 22:25
  • It is necessary for me and might not be possible to alter the structure now..I am in the task of designing a compiler and this is required for my Interpreter design. Wherein i need to keep track of the function arguments i.e ids to the values passed.. It might be a bit complicated to explain the overall structure . Commented Jun 27, 2014 at 22:35
  • If you're in the design phase for your compiler, then you can (and probably should) change it. Using a tuple for the map from id name to value is reasonable, but the nested tuples seem a design smelll Commented Jun 28, 2014 at 7:45
  • Thank you guys for helping with this. Particularly @Jasper-M solution was useful. I somewhat modified to fit my need. It was not easy to change as some of you suggested because that needs effort for me to change the checker stage together with Parser. Now i realise how i should have considered for Parser. Commented Jun 29, 2014 at 22:39

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.