Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smallest element in a list using higher-order functions

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.

like image 727
Swifty Avatar asked Mar 20 '26 12:03

Swifty


2 Answers

Use foldr. The accumulator begins as +inf.0. The combine-accumulator-and-element should return the smallest of the accumulator and the element.

like image 80
soegaard Avatar answered Mar 24 '26 22:03

soegaard


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
like image 43
Mulan Avatar answered Mar 24 '26 23:03

Mulan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!