Logic often requires you to find the lowest or highest value in an array. That’s easy just about everywhere. Sometimes though, you need to get the nearest number, and that can be a slight challenge, espeically in Scheme.
I wrote a little procedure called get-nearest+ that given a value, it will attempt to find the next largest value in that array. For example, given 24 and array of 10, 9, 35, 2, 29, 44, this procedure will return 29, because 29 comes right after 24.
I needed this logic in Scheme, but it’s easy enough to translate into C-based language too.
(define (get-nearest+ value lst)
(define ordered-lst (sort lst <))
(define (swap-value current found)
(if (> current found) current found))
(define (swap-indicator current found)
(if (> current found) #t #f))
(define (iterate fragment found break)
(if (or (null? fragment) break)
(if break
found
(car lst)
)
(iterate
(cdr fragment)
(swap-value (car fragment) found)
(swap-indicator (car fragment) found)
)
)
)
(iterate ordered-lst value #f)
)
The magic of this is the early return. By setting break to true at the same time as setting the new element in found, we return early and even larger elements are not returned.
Update
In my initial testing, I used this example given 24 and array of 10, 9, 35, 2, 29, 44. The problem with this is that if 25 comes after the 29, it would not be picked up. The early return sees to that. To remedy this, I use a sort-function to order everything. In this way, 25 will always come before 29 does.