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

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -