I'm writing my very first program in Scheme and after fighting off a bunch of syntax issues, I hit an infinite loop. I'm simply trying to retrieve the biggest number in a list and print it to the console. Here's what I have so far:
(define (max-num lst)
(cond [(= 0 (length lst)) (displayln "Your list is empty!")]
[(= 1 (length lst)) (displayln (car lst))]
;start comparing recursively
[>= (car lst) cdr(car lst) (max-num (list (car lst) (car(cdr lst))))]
(else (max-num(cdr lst))))
)
)
(max-num '(1 2 3 4 5))
(max-num '(-5 -3 -2 -13))
A very useful tool to debug programs is the Program Stepper. The stepper will show you how the program is evaluated one step at a time. The stepper only works for programs written in the teaching languages, so I have changed your program a little (I haven't changed the logic).
In DrRacket open a new file. Paste the program below (including the examples at the end). Choose the "Choose language..." item in the "Language" menu. Then choose the "Beginner" language. Finally click the "Step" button (next to the icon with a checkmark+looking glass).
(define (max-num lst)
(cond
[(= 0 (length lst)) "Your list is empty!"]
[(= 1 (length lst)) (car lst)]
[(>= (car lst) (cdr (car lst))) (max-num (list (car lst) (car(cdr lst))))]
[else (max-num(cdr lst))]))
(max-num (list 1 2 3 4 5))
(max-num (list -5 -3 -2 -13))
Click your way through the evaluation until you spot the error.
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