B
The problem is, you have the function. merge2 a declaration of function merge2Helper And nothing else.You don't cause this function anywhere. Let's call her in the last line in the body. merge2♪ Initiate the battery with an empty list:merge2Helper(listA, listB, List.empty[String])
But now your function still doesn't work, because logical mistakes have been made:The last step of the competition will lead to:case (Nil, Nil) = constituent NilResult of function merge2Helper The list is empty. We should get the battery back. listACC♪ You understand why. merge1 We have to go back. Nil♪ merge2 The battery?case (Nil, head2 :: tail2) = tie merge2Helper(tail2, listB, listACC ::: List(head2))This is where you change places. listA and listB I'll be right there. listA tail listB♪ And to the point of the tail listB You are. listB Totally. In every step of the course, the arguments are the same and your function endlessly cycling.Total:def merge2 (listA: List[String], listB: List[String]): List[String] = {
def merge2Helper (listA: List[String], listB: List[String], listACC: List[String]): List[String] =
(listA, listB) match {
case (Nil, Nil) => listACC
case (head1 :: tail1, Nil) => merge2Helper(tail1, listB, listACC ::: List(head1))
case (Nil, head2 :: tail2) => merge2Helper(listA, tail2, listACC ::: List(head2))
case (head1 :: tail1, head2 :: tail2) => merge2Helper(tail1, tail2, listACC ::: List(head1 + head2))
}
merge2Helper(listA, listB, Nil)
}
P.S. Can we make it easier?For two sheets scala Method zipwhich combines the elements of the first and second sheet into the list of vapours:List("a","b").zip(List("c","d")) // List(("a","c"),("b","d"))
However, zip It only works for the same length sheets, simply discarding the red pieces.I'll get it. zipAllwhich can take the meaning of default for the first or second sheet, in case some of them end up with elements:List("a","b").zipAll(List("c","d","e"), "", "") // List(("a","c"),("b","d"),("","e"))
Then it's a small one. Let's just put a couple of lines in line:List(("a","c"),("b","d"),("","e")).map{case (a,b) => a + b} // List("ac","bd","e")
Total:val l1 = List("a", "b", "c", "d")
val l2 = List("e", "f", "g", "h", "i", "j")
val t = l1.zipAll(l2,"","").map{case (a,b) => a+b}