I am trying to find the smallest element in a list of numbers.
This is trivial when using explicit recursion, but I am looking for a way to do this using solely the built-in higher-order functions, like
map,
filter,
and foldr.
In other words, I want to use a combination of these functions to get what I am looking for.
Use foldr. The accumulator begins as +inf.0. The combine-accumulator-and-element should return the smallest of the accumulator and the element.
I am trying to find the smallest element in a list of numbers.
The obvious way is to use the built-in min
#lang racket
(apply min '(5 2 3 6 4 0 9 -3 2 6))
;; => -3
However, if you have to implement your own min procedure, foldl will help you. I also made this procedure throw an error when attempting to use it on an empty list – much like the built-in min would do if you tried applying it to zero arguments.
#lang racket
(define (min xs)
(match xs
((list x xs ...) (foldl (λ (x acc) (if (< x acc) x acc))
x
xs))
(_ (error 'min "must use non-empty list"))))
(min '(5 2 3 6 4 0 9 -3 2 6))
;; => -3
(min '())
;; => min: must use non-empty list
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With