0

please help! how can i get the smallest value in a list in scheme? Please

How can I write a function that that finds the smallest Value in a list with nothing in it? The function would be called smallest, and it just kept the smallest number but how can I do this in scheme? For example: (smallest ‘(5 3 9 6) answer would be 3 i just have: (define (smallest x) … but i’m lost :/

8th Nov 2022, 2:13 AM
Julie Osbourne
1 Resposta
+ 2
Truthfully I am not a schemer, but I hope this will make sense. To determine the minimum, we can write a simple recursive algorithm. Some tools: min = compare two numbers car = first element of the list cdr = remaining elements of the list If the list has only one element, then the minimum is actually this single element. If the list has more elements, then we compare the first one, with the smallest of the remaining elements. (This will recursively run until only a single element is left). In code: (define (smallest x) (if (null? (cdr x)) (car x) (min (car x) (smallest (cdr x))))) One caveat, if the list is originally empty, it will blow up, but we could say it's OK because an empty list has no minimum. Maybe you can return null in that case to make it more elegant. Idea from https://stackoverflow.com/questions/36380482/function-in-scheme-that-shows-the-minimum-and-the-maximum-numbers-integers-in
8th Nov 2022, 5:46 AM
Tibor Santa
Tibor Santa - avatar