Smallest item 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'm looking for a way to do this using exclusively built-in functions of a higher order, for example

map,

filter,

and foldr.

In other words, I want to use a combination of these functions to get what I am looking for.

+4
source share
3 answers

Use foldr. Battery starts with + inf.0. The battery-cell-component should return the smallest of the battery and cell.

+1
source

I am trying to find the smallest element in a list of numbers.

min

#lang racket

(apply min '(5 2 3 6 4 0 9 -3 2 6))
;; => -3

, min, foldl. , - , min, .

#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
+1

You can also use the sort function in the list, and then take the first element of the sorted list:

(first (sort '(5 2 3 6 4 0 9 -3 2 6) <))
;; => -3
0
source

Source: https://habr.com/ru/post/1662791/


All Articles