Created
September 22, 2015 00:36
-
-
Save carymrobbins/fccaad6d947323791b7e to your computer and use it in GitHub Desktop.
Implement Haskell's insertWith for Scala Map types.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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