Skip to content

Instantly share code, notes, and snippets.

@raulraja
Last active June 26, 2019 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raulraja/118206b815293c89fb1fe7c93787902d to your computer and use it in GitHub Desktop.
Save raulraja/118206b815293c89fb1fe7c93787902d to your computer and use it in GitHub Desktop.
DefaultDictionary
package dictionary
/**
* A default dictionary is a map that provides a default concrete Monoid empty value for [B]
* Inspired by some of the examples of https://kotlinexpertise.com/default-map-in-kotlin/
* https://twitter.com/raulraja/status/1141697899383992325
*/
data class DefaultDictionary<A, B>(val empty: B, val underlying: Map<A, B> = emptyMap()) : Map<A, B> by underlying {
/**
* The empty value is always contained
*/
override fun containsValue(value: B): Boolean =
empty == value || underlying.containsValue(value)
/**
* if no value is found for key [A] defaults to the Monoid empty [B]
*/
override fun get(key: A): B? =
underlying[key] ?: empty
/**
* Combines this Dictionary with other Dictionary.
* Implements Semigroup.combine for all [A] under the assumption that the empty [B]
* is a constant indentity value such as 0 for Int, "" for String, emptyList() for List, etc.
*/
operator fun plus(other: DefaultDictionary<A, B>): DefaultDictionary<A, B> =
DefaultDictionary(empty, underlying + other.underlying)
companion object {
fun <A, B> of(empty: B, vararg pairs: Pair<A, B>): DefaultDictionary<A, B> =
DefaultDictionary(empty, pairs.toList().toMap())
fun <A> int(): DefaultDictionary<A, Int> = of(0)
/**
* Behavior as shown in the Python example
*/
fun <A, B> groupOcurrences(values: Collection<Pair<A, B>>): DefaultDictionary<A, List<B>> =
DefaultDictionary(emptyList(), values.toList().fold(emptyMap()) { acc, (a, b) ->
val listOfB = acc[a]
if (listOfB != null) acc + (a to (listOfB + b))
else acc + (a to listOf(b))
})
}
}
fun main() {
val d = DefaultDictionary.int<String>()
println(d["someKey"]) //0
val data = listOf("red" to 1, "blue" to 2, "red" to 3, "blue" to 4, "red" to 1, "blue" to 4)
println(DefaultDictionary.groupOcurrences(data)) //DefaultDictionary(empty=[], underlying={red=[1, 3, 1], blue=[2, 4, 4]})
}
@raulraja
Copy link
Author

Hi @kioba.
Is it still a valid override for Map if it just returns B? if it is then yes that signature is more accurate.
You are correct, plus is not well implemented. I'll edit it

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