Created
August 2, 2014 04:35
-
-
Save izmailoff/c10079c6574fa834c671 to your computer and use it in GitHub Desktop.
A class that wraps 2 maps in it and makes it look like a single map
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
// this is unfinished, but shows the idea | |
// It's an answer to: | |
// http://stackoverflow.com/questions/25028214/merging-scala-maps#comment38926797_25028214 | |
package com.izmailoff | |
class LazyMap[A, B, C, D](x: Map[A, B], y: Map[A, C], f: (Option[B], Option[C]) => Option[D]) | |
extends Map[A, D] { | |
def get(key: A): Option[D] = | |
f(x get key, None) orElse f(None, y get key) | |
def iterator: Iterator[(A, D)] = // wrong implementation - should produce unique keys | |
x.iterator.map { case (a, b) => a -> f(Some(b), None).get } ++ | |
y.iterator.map { case (a, b) => a -> f(None, Some(b)).get } | |
def +[B1 >: D](kv: (A, B1)): Map[A, B1] = ??? | |
//new LazyMap(x + kv, y, f) | |
def -(key: A): Map[A, D] = | |
new LazyMap(x - key, y - key, f) | |
} | |
object LazyMapMerge extends App { | |
val m1 = Map(1 -> "one", 2 -> "two") | |
val m2 = Map(1 -> 1L, 2 -> 2L, 3 -> 3L) | |
val m = new LazyMap(m1, m2, (first: Option[String], second: Option[Long]) => (first orElse second) map (_.toString)) | |
println("GET 1: " + m(1)) | |
println("ALL KEYS: " + m.keys) | |
println("ALL VALUES: " + m.values) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment