oponow
oponow

Reputation: 11

Issue with recursion

I am trying to do a questions in Java which involves taking a Lisp List and a integer, and multiplies all the items in the list by the integer but it has to use recursion. This is my code:

public static LispList<Integer> multipy(LispList<Integer> ls, int m){
    LispList<Integer> ls1 = LispList.empty();
    if(ls.isEmpty()){
        return ls1;
    }else{
        ls1.cons(ls.head() * b);
    }
    return multipy(ls1, m)
}

My idea was to first create a empty list, ls1. I then use a base case where I check whether the original list - ls - is empty and if so, to return the new List, ls1. If it isnt empty, I then multiply all items by the integer and pass it into ls1. I then call the method again at the end.

However my issue is this wont work as it will create a new List ls1 each time, thus destroying the list already created. I thought about passing in ls1 into the recursive call but this dosent work either as it operates on ls1 and not ls as required. Is there a way around this or do I have to use a iterative method to do it?

Upvotes: 0

Views: 67

Answers (1)

Andr&#233; Santos
Andr&#233; Santos

Reputation: 390

multiply(ls.tail(),m) gets you a list which contains all the values of the tail of ls multiplied. To that list you only have to add the head of ls multiplied, which you seem to do with the cons() method. So, it would be something like:

public static LispList<Integer> multipy(LispList<Integer> ls, int m){
     // No point making the else case if your
     // last statement of the block is a return
     if(ls.isEmpty()) return LispList.empty();

     return multiply(ls.tail(),m).cons(ls.head()*m);
}

I'm assuming your LispList has a tail() method.

Upvotes: 1

Related Questions