fold - Scala: using foldl to add pairs from list to a map? -
i trying add pairs list map using foldl. following error:
"missing arguments method /: in trait traversableonce; follow method `_' if want treat partially applied function"
code:
val pairs = list(("a", 1), ("a", 2), ("c", 3), ("d", 4)) def lsttomap(lst:list[(string,int)], map: map[string, int] ) = { (map /: lst) addtomap ( _, _) } def addtomap(pair: (string, int), map: map[string, int]): map[string, int] = { map + (pair._1 -> pair._2) }
what wrong?
you need swap input values of addtomap , put in parenthesis work:
def addtomap( map: map[string, int], pair: (string, int)): map[string, int] = { map + (pair._1 -> pair._2) } def lsttomap(lst:list[(string,int)], map: map[string, int] ) = { (map /: lst)(addtomap) }
missingfaktor's answer more concise, reusable, , scala-like.
Comments
Post a Comment