Created
December 22, 2013 02:38
-
-
Save pauldraper/8077831 to your computer and use it in GitHub Desktop.
Scala BiMap - a bidirectional map for Scala
This file contains 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
import scala.collection.mutable.Map | |
class BiMap[A,B] extends BiMapHelper(Map[A,B](), Map[B,A]()) { | |
} | |
object BiMap { | |
def apply[A,B](elems:(A,B)*) = new BiMap[A,B] ++= elems | |
} | |
/** | |
* This allows a bi-directional map to be created from any two maps. | |
* These maps must be the inverse of each other to work. | |
*/ | |
class BiMapHelper[A,B](forward:Map[A,B], backward:Map[B,A]) extends Map[A,B] { | |
def inverse = new BiMapHelper(backward, forward) | |
def get(key:A) = forward get key | |
def iterator = forward.iterator | |
def +=(kv:(A,B)) = { | |
forward += kv | |
backward += kv.swap | |
this | |
} | |
def -=(key:A) = { | |
backward --= (forward get key) | |
forward -= key | |
this | |
} | |
override def empty = { | |
forward.empty | |
backward.empty | |
this | |
} | |
override def size = forward.size | |
} | |
object BiMapHelper { | |
def apply[A,B](forward:Map[A,B], backward:Map[B,A]) = new BiMapHelper(forward, backward) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment