Skip to content

Instantly share code, notes, and snippets.

@kevinmeredith
Created November 14, 2013 03:55
Show Gist options
  • Select an option

  • Save kevinmeredith/7461099 to your computer and use it in GitHub Desktop.

Select an option

Save kevinmeredith/7461099 to your computer and use it in GitHub Desktop.
Creating a "bag" in Scala with foldLeft
// Given a list of items, return a Map[A -> Int] where A is an element and Int is how many times it appears
val result = List("a", "b", "a").foldLeft(Map[String, Int]())( (acc, el) =>
if (acc.contains(el) ) {
val x = acc.get(el).get
acc + (el -> (x+1))
}
else { acc + (el -> 1) } )
assert(result == Map("a" -> 2, "b" -> 1)
@kevinmeredith

Copy link
Copy Markdown
Author

Note - could've used acc(el) on line 4 per this post - http://stackoverflow.com/questions/19969225/getting-map-keys-value-cleanly

@dustingetz

Copy link
Copy Markdown
scala> Map[String, Int]().withDefaultValue(0)
res25: scala.collection.immutable.Map[String,Int] = Map()

scala> List("a","b","a").foldLeft(res25) { (acc, el) => acc + (el -> (acc(el) + 1)) }
res27: scala.collection.immutable.Map[String,Int] = Map(a -> 2, b -> 1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment