I wrote this function to find the longest common subsequence (LCS). For example, for two sequences of characters BANANA and ATANA, it returns AANA. Implementation is a naive, inefficient adaptation of a recursive algorithm, but for the purposes of this question it does not matter.
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 reorganize this function in the most general way . The current implementation works for any type of input sequence, but always returns a collection of type List [T]. I want to achieve the following behavior:
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 Seq s ...
It would be great if LCS could handle String s and Array s:
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 that using the Scala 2.8 collection library you can achieve at least the first requirement. We will be happy to see a βheavyβ machine, such as a higher grade polymorphism, class classes, CanBuildFrom, etc.
Thanks!