This function merges two sorted lists. It takes two lists as a parameter and returns one.
def merge(xs : List[Int], ys : List[Int]) : List[Int] = {
(xs, ys) match {
case (Nil, Nil) => Nil
case (Nil, ys) => ys
case (xs, Nil) => xs
case (x :: xs1, y :: ys1) =>
if(x < y) x :: merge(xs1, ys)
else y :: merge(xs, ys1)
}
}
I wanted to rewrite this function by changing the parameter type from List to Array, and it did not work. However, going from List to Seq it worked. Could you tell me what does not work with the Arrays?
def mergeDontWork(xs : Array[Int], ys : Array[Int]) : Array[Int] = {
(xs, ys) match {
case (Array.empty,Array.empty) => Array.empty
case (Array.empty, ys) => ys
case (xs, Array.empty) => xs
case (x +: xs1, y +: ys1) => if(x < y) x +: merge2(xs1, ys)
else y +: merge2(xs, ys1)
}
}
The error comes from that part of code : if(x < y) x +: merge2(xs1, ys)
: Array[Any] does not conform with the expected type Array[Int]
EDIT
I finally understood how to go from List to Array thanks to the solutions proposed by pedromss and Harald. I modified the function by making it tail recursive.
def mergeTailRecursion(xs : Array[Int], ys : Array[Int]) : Array[Int] ={
def recurse( acc:Array[Int],xs:Array[Int],ys:Array[Int]):Array[Int]={
(xs, ys) match {
case (Array(),Array()) => acc
case (Array(), ys) => acc++ys
case (xs, Array()) => acc++xs
case (a@Array(x, _*), b@Array(y, _*)) =>
if (x < y) recurse(acc:+x, a.tail, b)
else recurse( acc:+y, a, b.tail)
}
}
recurse(Array(),xs,ys)
}