Skip to content

Instantly share code, notes, and snippets.

@daviddenton
Created May 17, 2024 08:48
Show Gist options
  • Save daviddenton/6a3186834bdb9d096afbfa1ad7bcc51b to your computer and use it in GitHub Desktop.
Save daviddenton/6a3186834bdb9d096afbfa1ad7bcc51b to your computer and use it in GitHub Desktop.
Implement a map using only functions
// This is our map type
typealias FunctionalMap<K, V> = (K) -> V?
// An empty map never has the value
fun <K, V> emptyMap(): FunctionalMap<K, V> = { _ -> null }
// Match the key to the value or fallback
fun <K, V> FunctionalMap<K, V>.put(key: K, value: V): FunctionalMap<K, V> = { k ->
if (k == key) value else this(k)
}
// Retrieval is just calling the function
operator fun <K, V> FunctionalMap<K, V>.get(key: K): V? = this(key)
// Removal overrides any insertion
fun <K, V> FunctionalMap<K, V>.remove(key: K): FunctionalMap<K, V> = { k ->
if (k == key) null else this(k)
}
fun main() {
var aMap: FunctionalMap<String, Int> = emptyMap()
aMap = aMap.put("one", 1)
aMap = aMap.put("two", 2)
println(aMap["one"]) // Output: 1
println(aMap["two"]) // Output: 2
println(aMap["three"]) // Output: null
aMap = aMap.remove("one")
println(aMap["one"]) // Output: null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment