Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheme Racket Calculate Max Element in List Infinite Loop

Tags:

scheme

racket

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))
like image 872
aurora91 Avatar asked Jan 07 '23 16:01

aurora91


1 Answers

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.

like image 103
soegaard Avatar answered Mar 16 '23 15:03

soegaard