'Drracket: Finding highest value in a list without in built function
This assignment for a class I'm in has me pretty confused. I was able to get most of the function working but this one part is what's keeping me from completing it. I have two functions which is what I need one is to find the highest number value in a list (largest-num) and the other situates the list and is what refers to it (max-lon). I get the following error largest-num: expects only 1 argument, but found 2 and im not quite sure how to fix it. Code is listed:
(define (max-lon a-lon)
(local [
(define ACUMM (void))
(define lst (void))
;; lon number → number
;; Purpose: Return max(max of given list, given number)
;; Accumulator Invariant: accum = maximum in L - lst
(define (max-helper)
(if(empty? lst)
ACUMM
(begin
(set! ACUMM (largest-num (first lst) ACUMM))
(set! lst (rest lst))
(max-helper))))]
(if (empty? a-lon)
(error 'max-lon "An empty lon does not have a maximum.")
(begin
(set! ACUMM(first a-lon))
(set! lst (rest a-lon))
(max-helper)))))
(define (largest-num lst)
(cond
[(empty? (rest lst)) (first lst)]
[(< (first lst) (first (rest lst))) (largest-num (rest lst))]
[else (largest-num (cons (first lst) (rest (rest lst))))]))
Any suggestions would be great, thank you
Solution 1:[1]
largest-num can be simplified a lot more since all it has to do is compare two numbers which is ACUMM which is the accumulator/place in the list and first lst is what holds the highest number rather than processing the whole list which I assumed at first, here is fixed code:
(define (max-lon a-lon)
(local [
(define ACUMM (void))
(define lst (void))
(define (max-helper)
(if(empty? lst)
ACUMM
(begin
(set! ACUMM (largest? ACUMM (first lst)))
(set! lst (rest lst))
(max-helper))))]
(if (empty? a-lon)
(error 'max-lon "An empty lon does not have a maximum.")
(begin
(set! ACUMM(first a-lon))
(set! lst (rest a-lon))
(max-helper)))))
(define (largest? a b)
(if (> a b) a b))
Solution 2:[2]
(define (largest-num lst (acc -inf.0))
(cond ((empty? lst) acc)
((and acc (> (car lst) acc)) (largest-num (cdr lst) (car lst)))
(else (largest-num (cdr lst) acc))))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dima |
| Solution 2 | Gwang-Jin Kim |
