アイテムとパーツの間には暗黙の関係があります。少なくとも、アイテムをパーツオブジェクトに分解し、再構築するにはその逆を行う必要があります。
したがって、をとる"hello": String
と、f("hello")
return('h': Char, "ello": String)
が必要であり、逆関数g('h', "ello")
returnが必要"hello"
です。
したがって、いくつかのルールが守られている限り、そのような関数が2つある2つのタイプでも機能します。ルールは直感的に理解しやすいと思います。head
を使用してリストを再帰的に分解し、を使用してリストtail
を再構築する方法は、多かれ少なかれです。::
コンテキストバインドを使用して、通常のタイプにこれらの関数を提供できます。
(編集)
実際には、2つの型パラメーターがあるため、コンテキストバインドを実際に使用することはできませんが、これは私が念頭に置いていたものです。
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