I do not understand why my function to get the largest number does not want to work. If I am thinking about this correctly, if the first atom is smaller than the second atom the
There are 2 errors in your code:
1) in the else
clause, you should recursively call yourself, dropping the second element:
(else (getlargest (cons (car a_list) (cddr a_list))))))
2) you are missing the case of a list of only one element, where cadr
will fail
((null? (cdr a_list)) (car a_list))
And I personally prefer to yield #f
if the list is empty. Thus the code would look like
(define (getlargest a_list)
(cond
((null? a_list)
#f)
((null? (cdr a_list))
(car a_list))
((< (car a_list) (cadr a_list))
(getlargest (cdr a_list)))
(else
(getlargest (cons (car a_list) (cddr a_list))))))
Of course, a solution using foldl
is preferable:
(define (getlargest lst)
(foldl (lambda (e r) (if (or (not r) (> e r)) e r))
#f
lst))
or, probably slightly more efficient:
(define (getlargest lst)
(if (null? lst)
#f
(foldl (lambda (e r) (if (> e r) e r))
(car lst)
(cdr lst))))