1

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

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

9 Comments

Sure, the max function takes a list of numbers as input and returns the value of the number in the list which is the greatest. What I tried to do is assign the first value as the maximum ("y") using let, then step through each value in succession and compare it to the current maximum value. If it's greater, ("y") takes on a new value. I assumed (cadr x) would return null if there were no further values; would instead using use (cdr x) cause the same issue?
@Decency: Yes, you should use (cdr x) in the test. What do you think should be done with the answer from the recursive call (i.e., assuming you have a pair (x . z), what should be done with (max z))?
I'm not quite sure what you mean by the pair, but I'll try to respond. I want the answer from the recursive call to be passed up and compared to each (car x) that was taken recursively over the running of the program. I'm just not sure whether or not the scope of y is going to let me do this, and if it will, how to do so. I realize that I'm looking at this as essentially a do-while loop but I don't know if that is the correct approach for this language.
@Decency: Assume that x is the car of the list and m is the maximum element of the cdr of the list. What should the maximum of the whole list be?
The maximum of the whole list should either be x or m, whichever of the two is greater. That is what I intended my second if statement to test for, one element at a time.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.