Now this question is being written in Scala, but Scala is Java compatible. I will translate the java code into Scala.


// Write a recursive function "upto"
// that takes two Int parameters "start" and "end" and produces a "List[Int]"
// that counts DOWN from "start" to "end" (inclusive at both ends) one at
// a time. If "start < end", the empty list must be returned.


//This is what I have come up with so far. We had 10 questions, I have 9 of them done,
//just trying to figure this one out. I just need guidance on how to use the recursive
//call correctly

def otpu (start:Int, end:Int) : List[Int] = {  
 if (start < end)
  List()  //return empty list
   else
   (otpu( (start-1), 0) )	//returns 20, 19, 18, 17, 16, 15 (if upto(20, 15) entered.
}

Just point me in the right direction. I always have trouble grasping / defining the recursive function.

In Java, collection is a little bit different from what you are showing here. Also, it depends on how you implement recursive. You could add the value and call recursive function, or you call the function and let it return what you want back to you. Anyway, a simple idea is somewhat as follows:

/*
upto_recursive(start, end)
  if start==end  // base case, return the value of 'end'
    return list_with_end_value
  // concatenate the current start value and the return value
  return concatenate_list(start, upto_recursive(start+1, end))
*/

In the case above, the return value starts from "end" value and goes down to "start" value. Now it depends on how you want to return the list which contains 'end' value, and then 'concatenate_list' your list from the return there.

One catch for this recursive is that you would be screwed (the function goes into an infinite loop) if "start" is equal to or greater than "end" at the beginning of the call.

Thank you for helping me see outside of what I was thinking. I did not think of using the recursive method with in another method for terminating.

end up being:

def upto (start:Int, end:Int) : List[Int] = {  
if (start < end)
 Nil
else
 start :: upto( (start+1), end)   //  :: is concatenate in Scala
)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.