Reputation: 67115
Per this question:
Best way to merge two maps and sum the values of same key?
I would need to use scalaz to get what I want, however I am curious if anybody knew why the below does not work as I expect?
Map(1->2.0)+(1->1.0) //Map(1->1.0)
I would expect this to result in Map(1->3.0)
. But, it appears that maps only return the last key as shown by:
Map(1->1.0, 1->3.0) //Map(1->3.0)
So, based on the documentation
Adds two or more elements to this collection and returns a new collection.
and the above, my guess is that the map might store the values, but only return the last item? This is just not my intuition of what the add should do...maybe it is an efficiency move.
Once I have more of a moment, I will take a look at the code and try to figure it out from there, but wanted to ask here in case somebody already knew?
Upvotes: 2
Views: 5128
Reputation: 5069
@RexKerr's answer is perfectly correct, but I think doesn't emphasise the crucial misunderstanding here.
The +
operation on a Map
means put
- it puts a new key/value pair into the map (potentially replacing the existing pair for that key). It doesn't have anything to do with addition (and Rex's answer explains further how it cannot necessarily have anything to do with addition). You seem to come from a C# background, so you should think of:
myMap + (1, 1.0)
as being
myMap[1] = 1.0
The ability to insert a new key/value pair is a fundamental operation of a Map/Dictionary datatype. The ability you want to encode is something much less fundamental (and a special case for a more general ability to merge maps by key, as is mentioned in the question you reference, and here).
Upvotes: 1
Reputation: 167901
It has nothing to do with efficiency; it's typing. Map
plus elements returns a map of compatible type. You don't know the type, so you can't know to add numbers. You could list them instead, but Seq(2.0,1.0)
is not a supertype of 2.0
. So you'd end up having a map to Any
, which doesn't help you out at all when it comes to keeping your types straight, and you wouldn't have any way to replace an existing element with another.
So, +
adds a new element if the key does not exist, or replaces the existing element if the key does exist. (The docs should say so, though.)
If you want the "other" behavior, you need a more complex transformation, and that's what Scalaz' |+|
will do for you for the natural addition on the elements.
Upvotes: 6