I wrote the function to find longest common subsequence (LCS). For example, for two sequences of chars BANANA and ATANA it returns AANA. Implementation is naive inefficient adaptation of recursive algorithm, but it is irrelevant for purpose of this question.
def LCS[T](a: Seq[T], b: Seq[T]): Seq[T] = {
if (a.isEmpty || b.isEmpty)
Seq.empty
else if (a.head == b.head)
a.head +: LCS(a.tail, b.tail)
else {
val case1 = LCS(a.tail, b)
val case2 = LCS(a, b.tail)
if (case1.length > case2.length) case1 else case2
}
}
I want to refactor this function in most generic way possible. Current implementation works for any types of input sequences, but always returns collection of type List[T]. I want to achieve following behaviour:
LCS(List('B','A','N','A','N','A'), List('A','T','A','N','A')) -> List('A','A','N','A') LCS(Vector('B','A','N','A','N','A'), Vector('A','T','A','N','A')) -> Vector('A','A','N','A') ...and so on for all other Seqs...
It would be wonderful if LCS could also handle Strings and Arrays:
LCS("BANANA", "ATANA") -> "AANA" LCS(Array('B','A','N','A','N','A'), Array('A','T','A','N','A')) -> Array('A','A','N','A')
I believe with help of Scala 2.8 generic collection library it's possible to achieve at least first requirement. Will be glad to see "heavy" machinery like higher-kinded polymorphism, type classes, CanBuildFrom and so on.
Thanks!