Chris Arena
Chris Arena

Reputation: 1630

Scheme Max Function (Recursion)

The assignment is to define a function that accepts a single list as a parameter and outputs the maximum value of the list. I feel like my nesting "ifs" and "lets" are very excessive and the function is terminating prematurely without printing an answer. I've looked for an example of using let properly with recursion but have come up empty, the debugging features in DrRacket aren't very useful for tracing through recursive call.

Any help is appreciated, thanks.

(define max
(lambda (x)
  (let ((y (car x)))
    (if (null? (cdr x))
      y
      (let ((m (max(cdr x))))
           (if (> m y)
               m
               y)
     )))))

Upvotes: 1

Views: 6974

Answers (1)

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30969

I see a few bugs in your code: first, (null? (cadr x)) is not type-correct; x is a list of numbers, and so (cadr x) is a number, which will never be null. Also, you are not using y after the second time it is bound with let. Could you please try to describe in English what a max function on lists should do?

Upvotes: 2

Related Questions