Scala中有诸如双向地图之类的东西吗? [英] Is there such a thing as bidirectional maps in Scala?
本文介绍了Scala中有诸如双向地图之类的东西吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想链接2列唯一标识符,并且能够通过第二列值获得第一列值,并且能够通过第一列值获得第二列值.像
I'd like to link 2 columns of unique identifiers and be able to get a first column value by a second column value as well as a second column value by a first column value. Something like
Map(1 <-> "one", 2 <-> "two", 3 <-> "three")
在Scala中有这样的设施吗?
Is there such a facility in Scala?
实际上,我还需要更多:3列来选择一个三元组中的任何一个,而另一个则是三元组中的一个(在整个地图中,单个值永远不会满足一次).但是两栏双向地图也可以提供帮助.
Actually I need even more: 3 columns to select any in a triplet by another in a triplet (individual values will never be met more than once in the entire map). But a 2-column bidirectional map can help too.
推荐答案
我的BiMap方法:
object BiMap {
private[BiMap] trait MethodDistinctor
implicit object MethodDistinctor extends MethodDistinctor
}
case class BiMap[X, Y](map: Map[X, Y]) {
def this(tuples: (X,Y)*) = this(tuples.toMap)
private val reverseMap = map map (_.swap)
require(map.size == reverseMap.size, "no 1 to 1 relation")
def apply(x: X): Y = map(x)
def apply(y: Y)(implicit d: BiMap.MethodDistinctor): X = reverseMap(y)
val domain = map.keys
val codomain = reverseMap.keys
}
val biMap = new BiMap(1 -> "A", 2 -> "B")
println(biMap(1)) // A
println(biMap("B")) // 2
当然可以为<->
而不是->
添加语法.
Of course one can add syntax for <->
instead of ->
.
这篇关于Scala中有诸如双向地图之类的东西吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文