I’m trying to use recursion in the list and I need to go through all elements. Here is my code:
(define compare
(lambda (ls pred?)
(if (null? list)
#f
(pred? (list-ref ls (- (length ls) 2)) (list-ref ls (- (length ls) 1))))))
But it works only with last two elements. Result should be like this:
(compare '(1 2 3 4 5) <) -> #t
(compare '(1 2 8 4 5) <) -> #f
Do you have any idea what I should do?
You’re not using recursion anywhere in the code. In fact, it has errors and I don’t think you tested it thoroughly. For example:
ifcondition should be(null? ls)list-refis not the way to go when traversing a list in Scheme, for that in general you want to use recursion,car,cdr, etc.compareshould be called at some point!I believe this is what you intended, it’s not recursive but it’s the simplest way to implement the procedure:
Because this looks like homework I can only give you some hints for solving the problem from scratch, without using
apply. Fill-in the blanks:Notice that I used a named
letfor implementing the recursion, soloopis the recursive procedure here: you can see thatloopis being called insideloop. Alternatively you could’ve defined a helper procedure. I had to do this for taking into account the special case where the list is initially empty.The recursion works like this for the general case: two parameters are required,
prevstores the previous element in the list andlsthe rest of the list. at each point in the traversal we check to see if the predicates is false for the previous and the current element – if that is the case, then we return false. If not, we continue the recursion with a newprev(the current element) and the rest of the list. We keep going like this until the list is empty and only then we return true.