| author | wenzelm | 
| Tue, 18 Mar 2014 12:25:17 +0100 | |
| changeset 56202 | 0a11d17eeeff | 
| parent 55618 | 995162143ef4 | 
| child 56744 | 0b74d1df4b8e | 
| permissions | -rw-r--r-- | 
| 52975 | 1 | /* Title: Pure/General/multi_map.scala | 
| 2 | Module: PIDE | |
| 3 | ||
| 4 | Maps with multiple entries per key. | |
| 5 | */ | |
| 6 | ||
| 7 | package isabelle | |
| 8 | ||
| 55618 | 9 | |
| 52975 | 10 | import scala.collection.generic.{ImmutableMapFactory, CanBuildFrom}
 | 
| 11 | ||
| 12 | ||
| 13 | object Multi_Map extends ImmutableMapFactory[Multi_Map] | |
| 14 | {
 | |
| 15 | private val empty_val: Multi_Map[Any, Nothing] = new Multi_Map[Any, Nothing](Map.empty) | |
| 16 | override def empty[A, B] = empty_val.asInstanceOf[Multi_Map[A, B]] | |
| 17 | ||
| 18 | implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), Multi_Map[A, B]] = | |
| 19 | new MapCanBuildFrom[A, B] | |
| 20 | } | |
| 21 | ||
| 22 | ||
| 23 | final class Multi_Map[A, +B] private(rep: Map[A, List[B]]) | |
| 24 | extends scala.collection.immutable.Map[A, B] | |
| 25 | with scala.collection.immutable.MapLike[A, B, Multi_Map[A, B]] | |
| 26 | {
 | |
| 27 | /* Multi_Map operations */ | |
| 28 | ||
| 55488 
60c159d490a2
more integrity checks of theory names vs. full node names;
 wenzelm parents: 
52975diff
changeset | 29 | def iterator_list: Iterator[(A, List[B])] = rep.iterator | 
| 
60c159d490a2
more integrity checks of theory names vs. full node names;
 wenzelm parents: 
52975diff
changeset | 30 | |
| 52975 | 31 | def get_list(a: A): List[B] = rep.getOrElse(a, Nil) | 
| 32 | ||
| 33 | def insert[B1 >: B](a: A, b: B1): Multi_Map[A, B1] = | |
| 34 |   {
 | |
| 35 | val bs = get_list(a) | |
| 36 | if (bs.contains(b)) this | |
| 37 | else new Multi_Map(rep + (a -> (b :: bs))) | |
| 38 | } | |
| 39 | ||
| 40 | def remove[B1 >: B](a: A, b: B1): Multi_Map[A, B1] = | |
| 41 |   {
 | |
| 42 | val bs = get_list(a) | |
| 43 |     if (bs.contains(b)) {
 | |
| 44 |       bs.filterNot(_ == b) match {
 | |
| 45 | case Nil => new Multi_Map(rep - a) | |
| 46 | case bs1 => new Multi_Map(rep + (a -> bs1)) | |
| 47 | } | |
| 48 | } | |
| 49 | else this | |
| 50 | } | |
| 51 | ||
| 52 | ||
| 53 | /* Map operations */ | |
| 54 | ||
| 55 | override def stringPrefix = "Multi_Map" | |
| 56 | ||
| 57 | override def empty = Multi_Map.empty | |
| 58 | override def isEmpty: Boolean = rep.isEmpty | |
| 59 | ||
| 60 | override def keySet: Set[A] = rep.keySet | |
| 61 | ||
| 62 | override def iterator: Iterator[(A, B)] = | |
| 63 | for ((a, bs) <- rep.iterator; b <- bs.iterator) yield (a, b) | |
| 64 | ||
| 65 | def get(a: A): Option[B] = get_list(a).headOption | |
| 66 | ||
| 67 | def + [B1 >: B](p: (A, B1)): Multi_Map[A, B1] = insert(p._1, p._2) | |
| 68 | ||
| 69 | def - (a: A): Multi_Map[A, B] = | |
| 70 | if (rep.isDefinedAt(a)) new Multi_Map(rep - a) else this | |
| 71 | } |