Racket diagram. Calculate the maximum element in an infinite list loop.

I am writing my first program in Scheme and, fending off a bunch of syntactic problems, I end up in an endless loop. I am just trying to get the highest number in the list and print it to the console. Here is what I still have:

(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))
+4
source share
2 answers

A very useful tool for debugging programs is software Stepper. The pedometer will show you how the program is evaluated one step at a time. The pedometer works only for programs written in educational languages, so I changed your program a bit (I did not change the logic).

DrRacket . ( ). " ..." "". "Beginner". "" ( + ).

(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))

, .

+7

>= (car lst) cdr(car lst) , [(>= (car lst) cdr(car lst)) (max-num (list (car lst) (car(cdr lst))))]

+2

All Articles