(define (minim lst)
(COND
((NULL? (CDR lst)) (CAR lst))
(< (CAR lst) (minim (CDR lst)) (CAR lst))
(ELSE (minim (CDR lst))))
)
(minim '(3 4 2 9 3 8)) 3
I've figured out that it is the second line that is being evaluated and returning the (CAR of any list). What am I missing?
You are missing parenthesis in the second condition. This makes the "<" operator operate over three elements rather than two. The correct code looks like:
(define (minim lst)
(cond ((null? (cdr lst)) (car lst))
((< (car lst) (minim (cdr lst))) (car lst))
(else (minim (cdr lst)))) )
(minim '(3 4 2 9 3 8))
One note though: This code is not tail recursive. It goes all the way to the end of the list and starts comparing from there (i.e., the last element is compared with the one before that and so on).
A more efficient implementation would compare the first element to the current minimum, then proceed forward processing a shorter list every time. If you go this way, you will need an additional function argument holding the current minimum (this is equivalent to a left fold rather than the right fold you have implemented).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With