Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Tuple to Map?

Tags:

scala

Using Scala 2.11.8, I can append a key - value pair to a Map via:

scala> Map( (1 -> 1) ) + (2 -> 2)
res8: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2)

But how can I use tuple as the +'s argument?

scala> Map( (1 -> 1) ) + (2, 2)
<console>:12: error: type mismatch;
 found   : Int(2)
 required: (Int, ?)
       Map( (1 -> 1) ) + (2, 2)
                          ^

Nor does this work:

scala> Map( (1, 1) ) + (2, 2)
<console>:12: error: type mismatch;
 found   : Int(2)
 required: (Int, ?)
       Map( (1, 1) ) + (2, 2)
                        ^
<console>:12: error: type mismatch;
 found   : Int(2)
 required: (Int, ?)
       Map( (1, 1) ) + (2, 2)
                           ^

Map#+'s signature is:

+(kv: (A, B)): Map[A, B], so I'm not sure why it's not working.

EDIT

scala> Map( (1,1) ).+( (2, 2) )
res0: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2)

works, but why doesn't the above?

like image 220
Kevin Meredith Avatar asked Oct 24 '16 14:10

Kevin Meredith


People also ask

How do I add a tuple to a map?

You have to use map::find() and map::insert(). find() returns an iterator to a map element, which is a pair<int, list>, or it returns end(). If the iterator == end(), you need to add a pair<int, list> to the map.

Can you add tuples in python?

In Python, since tuple is immutable, you cannot update it, i.e., you cannot add, change, or remove items (elements) in tuple . tuple represents data that you don't need to update, so you should use list rather than tuple if you need to update it.

How to add the elements of two tuples together?

Concatenating and Multiplying Tuples Concatenation is done with the + operator, and multiplication is done with the * operator. Because the + operator can concatenate, it can be used to combine tuples to form a new tuple, though it cannot modify an existing tuple. The * operator can be used to multiply tuples.


1 Answers

In Scala, any binary operation (*,+, etc.) is actually a method of the class of the first element in the operation.

So, for example, 2 * 2 is equivalent to 2.*(2), because * is just a method of the class Int.

What is happening when you type Map( (1 -> 1) ) + (2, 2) is that Scala recognizes that you are using the + method of the Map class. However it thinks that you are trying to pass multiple values to this method because it defaults to interpreting the opening paren as the beginning of a parameter list (this is a (reasonable) design decision).

The way you resolve this is to wrap the tuple in another pair of parens or to use the -> syntax (with parens, because operator precedence).

scala> Map( (1 -> 1) ) + ((2, 2))
res0: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2)

scala> Map( (1 -> 1) ) + (2 -> 2)
res1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2)
like image 189
evan.oman Avatar answered Oct 19 '22 06:10

evan.oman