Why does Map's + operator need double parentheses? - scala

For example:
val m = Map[Int, Int]()
m + (1, 1) // doesn't work!
m + ((1, 1)) // works!
I know (1, 1) is a Tuple2, but then why doesn't the former work? Can I avoid this quirky double parentheses?

m + (1, 1) is the same thing as m.+(1, 1), that is, it's a function call with two integer arguments rather than a call with a single Tuple2 argument.
You can however use -> which forms a Tuple without parentheses thus:
val m = Map[Int, Int]()
m + 1 -> 1 // works!
or perhaps more usefully:
var m = Map[Int, Int]()
m += 1 -> 1 // works!

In the case of m + (1, 1) Scala thinks that you want to call method + with 2 arguments, i.e. m.+(1, 1), and fails because such method does not exist.
You could write it in such a way when compiler has no doubts regarding number of passed arguments:
As mentioned before:
m + (1 -> 1)
or
val m = Map[Int, Int]()
val t = (1, 1)
m + t

Your script doesn't work because you try to use method that doesn't exist. In your case Scala thinks that you want to use function + with two arguments (Int and Int) instead of one (Tuple2).
The best way to solve the problem it is use -> operator. Here is example code:
scala> val m = Map[Int, Int]()
m: scala.collection.immutable.Map[Int,Int] = Map()
scala> m + (1 -> 1)
res0: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1)

Related

Sum of Values based on key in scala

I am new to scala I have List of Integers
val list = List((1,2,3),(2,3,4),(1,2,3))
val sum = list.groupBy(_._1).mapValues(_.map(_._2)).sum
val sum2 = list.groupBy(_._1).mapValues(_.map(_._3)).sum
How to perform N values I tried above but its not good way how to sum N values based on key
Also I have tried like this
val sum =list.groupBy(_._1).values.sum => error
val sum =list.groupBy(_._1).mapvalues(_.map(_._2).sum (_._3).sum) error
It's easier to convert these tuples to List[Int] with shapeless and then work with them. Your tuples are actually more like lists anyways. Also, as a bonus, you don't need to change your code at all for lists of Tuple4, Tuple5, etc.
import shapeless._, syntax.std.tuple._
val list = List((1,2,3),(2,3,4),(1,2,3))
list.map(_.toList) // convert tuples to list
.groupBy(_.head) // group by first element of list
.mapValues(_.map(_.tail).map(_.sum).sum) // sums elements of all tails
Result is Map(2 -> 7, 1 -> 10).
val sum = list.groupBy(_._1).map(i => (i._1, i._2.map(j => j._1 + j._2 + j._3).sum))
> sum: scala.collection.immutable.Map[Int,Int] = Map(2 -> 9, 1 -> 12)
Since tuple can't type safe convert to List, need to specify add one by one as j._1 + j._2 + j._3.
using the first element in the tuple as the key and the remaining elements as what you need you could do something like this:
val list = List((1,2,3),(2,3,4),(1,2,3))
list: List[(Int, Int, Int)] = List((1, 2, 3), (2, 3, 4), (1, 2, 3))
val sum = list.groupBy(_._1).map { case (k, v) => (k -> v.flatMap(_.productIterator.toList.drop(1).map(_.asInstanceOf[Int])).sum) }
sum: Map[Int, Int] = Map(2 -> 7, 1 -> 10)
i know its a bit dirty to do asInstanceOf[Int] but when you do .productIterator you get a Iterator of Any
this will work for any tuple size

Why Scala REPL shows tuple type for Map expression?

Scala REPL gives the same type for both expressions - (tuple? -- strange!). Yet ("a" ->1) which is a Map I can add to map and ("a", 1)can not. Why Scala REPL shows tuple type type for Map expression?
scala> :t ("a" -> 1)
(String, Int)
scala> :t ("a",1)
(String, Int)
scala> val m = Map.empty[String, Int]
m: scala.collection.immutable.Map[String,Int] = Map()
scala> m + ("a",1)
<console>:9: error: type mismatch;
found : String("a")
required: (String, ?)
m + ("a",1)
^
scala> m + ("a" ->1)
res19: scala.collection.immutable.Map[String,Int] = Map(a -> 1)
Scala thinks a + (b,c) means you are trying to call the + method with two arguments, which is a real possibility since maps do have a multi-argument addition method so you can do things like
m + (("a" -> 1), ("b" -> 2))
the solution is simple: just add an extra set of parentheses so it's clear that (b,c) is in fact a tuple being passed as a single argument.
m + (("a", 1))
Actually, the reason for this is that Predef: http://www.scala-lang.org/api/current/index.html#scala.Predef$ (which is always in scope in Scala) contains an implicit conversion from Any to ArrowAssoc (the method implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A])
ArrowAssoc contains the method -> which converts it to a tuple.
So basically you are doing any2ArrowAssoc("a").->(1) which returns ("a",1).
From repl:
any2ArrowAssoc("a").->(1)
res1: (java.lang.String, Int) = (a,1)
Furthermore, you can work on immutable hashmaps like this:
val x = HashMap[Int,String](1 -> "One")
x: scala.collection.immutable.HashMap[Int,String] = Map((1,One))
val y = x ++ HashMap[Int,String](2 -> "Two")
y: scala.collection.immutable.Map[Int,String] = Map((1,One), (2,Two))
val z = x + (3 -> "Three")
z: scala.collection.immutable.HashMap[Int,String] = Map((1,One), (3,Three))

Multi-key Map in Scala

How can I create a Map in Scala which does not only take a single parameter as key, but rather two or three.
val map = //..?
map("abc", 1) = 1
println(map("abc", 2)) // => null
println(map("abc", 1)) // => 1
I tried using tuples as a key, but then I have to assign values like this
map(("abc", 1)) = 1
Can I somehow get rid of the inner parentheses?
You could also use
map += ("abc", 1) -> 1
If the map key represents something (e.g. user info) and if you want to add clarity to your code (especially if you have 3 elements in the key), I would go with a case class as the key. Case classes have equals and hashcode implemented so you can safely use them as keys in a map. The code would be more verbose though:
case class MapKey(s: String, i: Int, d: Double)
val map = Map[MapKey, X](MapKey("a", 1, 1.1) -> "value1", MapKey("b", 2, 2.2) -> "value2")
val map2 = map + (MapKey("c", 3, 3.3) -> "value3")
//or for mutable map
map(MapKey("d", 4, 4.4)) = "value4"
//or
map += MapKey("e", 5, 5.5) -> "value5"
You can add your own enhancement to Map that will do the trick:
import collection.mutable.Map
implicit class EnhancedMap[A,B,C](m: Map[(A,B),C]) {
def update(a: A, b: B, c: C) { m((a,b)) = c }
}
then
val map = Map(("abc", 1) -> 0)
map("abc", 1) = 1
works just fine.
You can use -> syntax for tuples:
map("abc" -> 1) = 1
I got compiling errors using Luigi Plinge's approach. The following approach works for me, which is simpler.
scala> var b = Map[(Int, Int), Int]()
b: scala.collection.mutable.Map[(Int, Int),Int] = Map()
scala> b = b + ((1,1)->2)
b: scala.collection.mutable.Map[(Int, Int),Int] = Map((1,1) -> 2)
scala> b
res15: scala.collection.mutable.Map[(Int, Int),Int] = Map((1,1) -> 2)
scala> b = b + ((1,2)->2)
b: scala.collection.mutable.Map[(Int, Int),Int] = Map((1,1) -> 2, (1,2) -> 2)
scala> b(1,1)
res16: Int = 2
scala> b(1,2)
res17: Int = 2

Scala Map from tuple iterable

Constructing scala.collection.Map from other collections, I constantly find myself writing:
val map = Map(foo.map(x=>(x, f(x)))
However, this doesn't really work since Map.apply takes variable arguments only - so I have to write:
val map = Map(foo.map(x=>(x, f(x)) toSeq :_*)
to get what I want, but that seems painful. Is there a prettier way to construct a Map from an Iterable of tuples?
Use TraversableOnce.toMap which is defined if the elements of a Traversable/Iterable are of type Tuple2. (API)
val map = foo.map(x=>(x, f(x)).toMap
Alternatively you can use use collection.breakOut as the implicit CanBuildFrom argument to the map call; this will pick a result builder based on the expected type.
scala> val x: Map[Int, String] = (1 to 5).map(x => (x, "-" * x))(collection.breakOut)
x: Map[Int,String] = Map(5 -> -----, 1 -> -, 2 -> --, 3 -> ---, 4 -> ----)
It will perform better than the .toMap version, as it only iterates the collection once.
It's not so obvious, but this also works with a for-comprehension.
scala> val x: Map[Int, String] = (for (i <- (1 to 5)) yield (i, "-" * i))(collection.breakOut)
x: Map[Int,String] = Map(5 -> -----, 1 -> -, 2 -> --, 3 -> ---, 4 -> ----)
val map = foo zip (foo map f) toMap

Scala: How to create a Map[K,V] from a Set[K] and a function from K to V?

What is the best way to create a Map[K,V] from a Set[K] and function from K to V?
For example, suppose I have
scala> val s = Set(2, 3, 5)
s: scala.collection.immutable.Set[Int] = Set(2, 3, 5)
and
scala> def func(i: Int) = "" + i + i
func: (i: Int)java.lang.String
What is the easiest way of creating a Map[Int, String](2 -> "22", 3 -> "33", 5 -> "55")
You can use foldLeft:
val func2 = (r: Map[Int,String], i: Int) => r + (i -> func(i))
s.foldLeft(Map.empty[Int,String])(func2)
This will perform better than Jesper's solution, because foldLeft constructs the Map in one pass. Jesper's code creates an intermediate data structure first, which then needs to be converted to the final Map.
Update: I wrote a micro benchmark testing the speed of each of the answers:
Jesper (original): 35s 738ms
Jesper (improved): 11s 618ms
dbyrne: 11s 906ms
Rex Kerr: 12s 206ms
Eastsun: 11s 988ms
Looks like they are all pretty much the same as long as you avoid constructing an intermediate data structure.
What about this:
(s map { i => i -> func(i) }).toMap
This maps the elements of s to tuples (i, func(i)) and then converts the resulting collection to a Map.
Note: i -> func(i) is the same as (i, func(i)).
dbyrne suggests creating a view of the set first (see his answer and comments), which prevents an intermediate collection from being made, improving performance:
(s.view map { i => i -> func(i) }).toMap
scala> import collection.breakOut
import collection.breakOut
scala> val set = Set(2,3,5)
set: scala.collection.immutable.Set[Int] = Set(2, 3, 5)
scala> def func(i: Int) = ""+i+i
func: (i: Int)java.lang.String
scala> val map: Map[Int,String] = set.map(i => i -> func(i))(breakOut)
map: Map[Int,String] = Map(2 -> 22, 3 -> 33, 5 -> 55)
scala>
In addition to the existing answers,
Map() ++ set.view.map(i => i -> f(i))
is pretty short and performs as well as the faster answers (fold/breakOut).
(Note the view to prevent creation of a new collection; it does the remapping as it goes.)
The other solutions lack creativity. Here's my own version, though I'd really like to get rid of the _.head map.
s groupBy identity mapValues (_.head) mapValues func
As with all great languages, there's a million ways to do everything.
Here's a strategy that zips the set with itself.
val s = Set(1,2,3,4,5)
Map(s.zip(s.map(_.toString)).toArray : _*)
EDIT: (_.toString) could be replaced with some function that returns something of type V
Without definition of func(i: Int) using "string repeating" operator *:
scala> s map { x => x -> x.toString*2 } toMap
res2: scala.collection.immutable.Map[Int,String] = Map(2 -> 22, 3 -> 33, 5 -> 55)