Item 和 Part 之间存在隐含关系。至少你需要将一个 Item 分解为 Part 对象,而重构你需要做相反的事情。
所以取"hello": String,你需要让f("hello")返回('h': Char, "ello": String),你需要反函数g('h', "ello")返回"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?