0

I'm trying to practice recursive and tail recursive functions using Scala, I've created a tail recursive function to sum the values in two lists. I'm trying to do the same with recursion too but the only way I could think of was to modify the parameter each time the method was called like tail recursion. Can you help me out?

def callTailRecursive(list1 : List[Int], list2 : List[Int]) : List[Int] = { def callHelper(list1 : List[Int], list2 : List[Int], outputList : List[Int]): List[Int] ={ if(!list1.isEmpty && !list2.isEmpty){ callHelper(list1.tail,list2.tail,outputList:+(list1.head + list2.head)) }else if(list1.isEmpty && !list2.isEmpty){ callHelper(list1,list2.tail,outputList:+(list2.head)) }else if(!list1.isEmpty && list2.isEmpty){ callHelper(list1.tail,list2,outputList:+(list1.head)) }else{ outputList } } callHelper(list1,list2,List()) } def callRecursive(n : Int, list1 : List[Int], list2 : List[Int], outputList : List[Int]): List[Int] = { } 
1
  • 2
    "tail recursive" is a subset of "recursive". Every tail recursive function is, almost definitionally, a recursive function. What are you trying to do? Write a function that specifically isn't tail recursive? That sounds akin to trying to write a function with the requirement that it take at least an hour to run. You're optimizing for negative things. Commented Nov 11, 2021 at 1:37

1 Answer 1

6

Pattern matching. It's the bee's knees.

def callRecursive(list1: List[Int], list2: List[Int]): List[Int] = (list1,list2) match { case (hd1::tl1, hd2::tl2) => (hd1+hd2) :: callRecursive(tl1, tl2) case (_, Nil) => list1 case (Nil, _) => list2 } def notRecursive(list1: List[Int], list2: List[Int]): List[Int] = list1.zipAll(list2, 0, 0).map{case (a,b) => a+b} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.