How about this:
def process[A](xs: List[A], ys: List[A], n: Int): List[A] = if(xs.size <= n || ys.size == 0) xs else xs.take(n):::ys.head::process(xs.drop(n),ys.tail,n)
scala> process(a,b,n) res8: List[Int] = List(1, 2, 3, 101, 4, 5, 6, 102, 7, 8, 9, 103, 10, 11, 12, 13, 14, 15) scala> val a = List(1,2,3,4,5,6,7,8,9,10,11) a: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) scala> process(a,b,n) res9: List[Int] = List(1, 2, 3, 101, 4, 5, 6, 102, 7, 8, 9, 103, 10, 11) scala> val a = List(1,2,3,4,5,6,7,8,9) a: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9) scala> process(a,b,n) res10: List[Int] = List(1, 2, 3, 101, 4, 5, 6, 102, 7, 8, 9) scala> val a = List(1,2,3,4,5,6,7,8) a: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8) scala> process(a,b,n) res11: List[Int] = List(1, 2, 3, 101, 4, 5, 6, 102, 7, 8)
Your request: βIf the length of the 1st list is less than n, there are no insert resultsβ, then my code should change to:
def process[A](xs: List[A], ys: List[A], n: Int): List[A] = if(xs.size < n || ys.size == 0) xs else xs.take(n):::ys.head::process(xs.drop(n),ys.tail,n)