Created
December 4, 2014 22:43
-
-
Save ezhulenev/4abfa0adf01a12c75761 to your computer and use it in GitHub Desktop.
Deep TreeMap conversion
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
import scala.collection.immutable.TreeMap | |
trait ToTreeMap[A] { | |
type Result | |
def treeMap(x: A): Result | |
} | |
trait LowerPriorityToTreeMap { | |
implicit def plainMap[K, V](implicit ord: Ordering[K]): ToTreeMap[Map[K, V]] = | |
new ToTreeMap[Map[K, V]] { | |
type Result = TreeMap[K, V] | |
def treeMap(x: Map[K, V]): Result = TreeMap(x.toArray: _*) | |
} | |
} | |
object ToTreeMap extends LowerPriorityToTreeMap { | |
implicit def nestedMap[K, V](implicit inner: ToTreeMap[V], ord: Ordering[K]): ToTreeMap[Map[K, V]] = { | |
new ToTreeMap[Map[K, V]] { | |
type Result = TreeMap[K, inner.Result] | |
def treeMap(x: Map[K, V]): Result = TreeMap(x.mapValues(v => inner.treeMap(v)).toArray: _*) | |
} | |
} | |
implicit class MapOps[K, V](map: Map[K, V]) { | |
def asTreeMap(implicit as: ToTreeMap[Map[K, V]]) = as.treeMap(map) | |
} | |
} | |
object test extends App { | |
import pellucid.data.util.ToTreeMap._ | |
val map: Map[Int, Map[Int, Map[Int, String]]] = Map(1000 -> Map(100 -> Map(10 -> "aa", 1 -> "bb"))) | |
val tm: TreeMap[Int, TreeMap[Int, TreeMap[Int, String]]] = map.asTreeMap | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment