(define (iterate list)
(cond
((null? list) '())
So far all I have is that it checks if it is a null list. If it is then it passes the empty list. What I am trying to do is I want to iterate through the list until I find the last element. I want to loop the list cdr until cdr shows up as null. I understand the logic but not the syntax.
For a list (1 2 3 4) I want to be able to see that 4 is the last element.
CodePudding user response:
If you are sure the next element isn't null?
then you call the recursion in the exact same manner as you call the function otherwise. eg.
(iterate (cdr list))
This is not special for Scheme. eg. in JavaScript you can call iterate(...)
from both outside and inside of iterate
.
CodePudding user response:
First of all, the name of the function should reflect what it does.
Let's call it get-last
.
Second, you need to consider the different types of lists that you will receive. For instance,
- what does your function do when the list is empty?
- what if there is only one element?
- what if there are more?
(define (get-last list)
(cond
[(null? list) (raise 'empty-list)]
[(null? (cdr list)) (car list)]
[else (get-last (cdr list))]
))
(Notice that I use square brackets []
for the cases of cond
because I think it's more readable. But you can use parentheses ()
instead if you want.)
This is now called with (get-last '(1 2 3 4))
.