mardi, novembre 29, 2011

Concrete Scala Map and SortedMap example

This is a concrete Scala Map and SortedMap example.
I wrote this post because I found it very difficult to find the right information when trying to get a concrete Map and SortedMap.
class StringOrder extends Ordering[String] {
 override def compare(s1: String, s2: String) = s1.compare(s2)
}
class MyParameter() {}


class ZeParameters(val pairs:List[(String,MyParameter)] = Nil) extends SortedMap[String,MyParameter] {
 /**** Minimal Map stuff begin ****/
 lazy val keyLookup = Map() ++ pairs
 override def get(key: String): Option[MyParameter] = keyLookup.get(key)
 override def iterator: Iterator[(String, MyParameter)] = pairs.reverseIterator
 override def + [B1 >: MyParameter](kv: (String, B1)) = {
  val (key:String, value:MyParameter) = kv
  new ZeParameters((key,value) :: pairs)
 }
 override def -(key: String): ZeParameters  = new ZeParameters(pairs.filterNot(_._1 == key))
 /**** Minimal map stuff end ****/
 /**** Minimal SortedMap stuff begin ****/
 def rangeImpl (from: Option[String], until: Option[String]): ZeParameters = {
  val out = pairs.filter((p: (String, MyParameter)) => {
   var compareFrom = 0
   from match {
    case Some(s) => compareFrom = p._1.compare(s)
    case _ =>
   }
   var compareUntil = 0
   until match {
    case Some(s) => compareUntil = p._1.compare(s)
    case _ =>
   }
   compareFrom>=0 && compareUntil<=0
  })
  new ZeParameters(out)
 }
 
 def ordering: Ordering[String] = new StringOrder
 /**** Minimal SortedMap stuff end ****/
}
Do not forget that you can also transform your map into a list and then use sortBy:
class ListSort {
  println(List((1.0,"zob"),(1.2,"zab"),(0.9,"zub")).sortBy{_._1})
}

Aucun commentaire: