dictionary - Scala concatenate maps from a list -


having val maplist: list[map[string, int]], want like:

val map = maplist foldleft (map[string, int]()) ( _ ++ _ ) 

or

val map = maplist foldleft (map[string, int]())  ( (m1: map[string, int], m2: map[string, int]) => m1 ++ m2 ) 

neither option compiled (first says "missing parameter type expanded function (x, y) => x ++ y" , second says "type mismatch; found (map[string, int], map[string, int]) => map[string, int]; required: string").

i want achieve classical solution concatenating list of immutable maps such list( map("apple" -> 5, "pear" -> 7), map("pear" -> 3, "apricot" -> 0) ) produce map("apple" -> 5, "pear" -> 10, "apricot" -> 0).

using scala 2.10.5.

you need add dot before foldleft. can use spaces instead of dots under specialized conditions, such methods 1 parameter (arity-1 methods):

val map = maplist.foldleft(map[string, int]()) ( _ ++ _ ) 

you can read more method invocation best practices here.

you might interested in reduce methods, specialized versions of fold methods, return type same type of elements of collection. example reduceleft uses first element of collection seed foldleft. of course, since relies on first element's existence, throw exception if collection empty. since reduceleft takes 1 parameter, can more use space invoke method:

maplist.reduceleft( _ ++ _) maplist reduceleft(_ ++ _) 

finally, should note doing here merging maps. when using ++ merge maps, override keys present in map – you won't adding values of duplicate keys. if wanted that, follow answers provided here, , apply them foldleft or reduceleft. example:

maplist reduceleft { (acc, next) =>      (acc.tolist ++ next.tolist).groupby(_._1).tomap.mapvalues(_.map(_._2).sum)  } 

or differently:

maplist.map(_.toseq).reduceleft(_ ++ _).groupby(_._1).tomap.mapvalues(_.map(_._2).sum) 

and, if you're using scalaz, concisely:

maplist reduceleft { _ |+| _ } 

Comments