Item 和 Part 之间存在隐含的关系。至少,您需要将 Item 分解为 Part 对象,而要重构,您需要做相反的事情。
因此"hello": String
,您需要有f("hello")
return('h': Char, "ello": String)
并且需要反函数g('h', "ello")
return "hello"
。
因此,只要遵循一些规则,具有两个这样的功能的任何两种类型都可以。我认为规则很容易直觉。它或多或少是如何使用递归分解列表head
并tail
使用重建它的::
您可以使用上下文绑定来为常用类型提供这些功能。
(编辑)
实际上我不能真正使用上下文绑定,因为有两个类型参数,但这是我的想法:
trait R[Item, Part] {
def decompose(item: Item): (Part, Item)
def recompose(item: Item, part: Part): Item
def empty: Item
}
class NotATrie[Item, Part](item: Item)(implicit rel: R[Item, Part]) {
val brokenUp = {
def f(i: Item, acc: List[Part] = Nil): List[Part] = {
if (i == rel.empty) acc
else {
val (head, tail) = rel.decompose(i)
f(tail, head :: acc)
}
}
f(item)
}
def rebuilt = (rel.empty /: brokenUp)( (acc, el) => rel.recompose(acc, el) )
}
然后我们提供一些隐式对象:
implicit object string2R extends R[String, Char] {
def decompose(item: String): (Char, String) = (item.head, item.tail)
def recompose(item: String, part: Char): String = part + item
def empty: String = ""
}
implicit object string2RAlt extends R[String, Int] {
def decompose(item: String): (Int, String) = {
val cp = item.codePointAt(0)
val index = Character.charCount(cp)
(cp, item.substring(index))
}
def recompose(item: String, part: Int): String =
new String(Character.toChars(part)) + item
def empty: String = ""
}
val nat1 = new NotATrie[String, Char]("hello")
nat1.brokenUp // List(o, l, l, e, h)
nat1.rebuilt // hello
val nat2 = new NotATrie[String, Int]("hello\ud834\udd1e")
nat2.brokenUp // List(119070, 111, 108, 108, 101, 104)
nat2.rebuilt // hello