Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Created September 22, 2015 00:36
Show Gist options
  • Select an option

  • Save carymrobbins/fccaad6d947323791b7e to your computer and use it in GitHub Desktop.

Select an option

Save carymrobbins/fccaad6d947323791b7e to your computer and use it in GitHub Desktop.
Implement Haskell's insertWith for Scala Map types.
implicit class RichMap[K, +V](private val m: Map[K, V]) extends AnyVal {
/**
* Based on Haskell's insertWith for Map types.
* If the provided key already exists in the map, the value inserted will be f(newValue, oldValue).
*/
def insertWith[V1 >: V](k: K, v: V1, f: (V1, V1) => V1): Map[K, V1] = {
m.updated(k, m.get(k).map(f(v, _)).getOrElse(v))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment